Possible bug in ASP.NET MVC with form values being replaced

后端 未结 12 708
抹茶落季
抹茶落季 2020-11-29 00:41

I appear to be having a problem with ASP.NET MVC in that, if I have more than one form on a page which uses the same name in each one, but as different types (radio/hidden/e

12条回答
  •  悲哀的现实
    2020-11-29 00:47

    As others have suggested, I went with using direct html code instead of using the HtmlHelpers (TextBoxFor, CheckBoxFor, HiddenFor etc.).

    The problem though with this approach is that you need to put the name and id attributes as strings. I wanted to keep my model properties strongly-typed so I used the NameFor and IdFor HtmlHelpers.

    
    

    Update: Here's a handy HtmlHelper extension

        public static MvcHtmlString MyHiddenFor(this HtmlHelper helper, Expression> expression, object htmlAttributes = null)
        {
            return new MvcHtmlString(
                string.Format(
                    @"",
                    helper.IdFor(expression),
                    helper.NameFor(expression),
                    GetValueFor(helper, expression)
                ));
        }
    
        /// 
        /// Retrieves value from expression
        /// 
        private static string GetValueFor(HtmlHelper helper, Expression> expression)
        {
            object obj = expression.Compile().Invoke(helper.ViewData.Model);
            string val = string.Empty;
            if (obj != null)
                val = obj.ToString();
            return val;
        }
    

    You can then use it like

    @Html.MyHiddenFor(m => m.Name)
    

提交回复
热议问题