ASP.NET MVC 2.0 Html.HiddenFor HtmlHelper extension does not return a value

We try to be type safe in our views and use the new ExpressionInputExtenssion HtmlHelpers, but we see some inconsistent results. We have a view that looks like this:

ViewData.Model.FooID = <%= ViewData.Model.FooID %><
Model.FooID = <%= Model.FooID  %>       
<%= Html.HiddenFor(x=>x.FooID) %>  

But what we see in the visualized representation is this:

ViewData.Model.FooID = 515b0403-e75b-4bd7-9b60-ef432f39d338
Model.FooID = 515b0403-e75b-4bd7-9b60-ef432f39d338    
<input id="FooID" name="FooID" type="hidden" value="" />  

I can manually add this:

<input id="FooID" name="FooID" type="hidden" value="<%= Model.FooID %>" />

But now we are no longer there, but surprisingly when I do this, Html.HiddenFor always has the correct meaning.

+5
source share
4 answers

, , , FoodID . GUID?

, , GUID...

debbuging?

+2

, , ( , ), , , , , , , , . .

+1

,

@Html.HiddenForField(m => m.Location.CityRequired)

public static class HiddenExtensions
{
    public static MvcHtmlString HiddenForField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression) where TModel : class
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var value = metadata.Model;
        return htmlHelper.HiddenForField(expression, value);
    }

    public static MvcHtmlString HiddenForField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object value) where TModel : class
    {
        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
        var tag = new TagBuilder("input");
        tag.GenerateId(fullName);
        tag.Attributes.Add("type", "hidden");
        tag.Attributes.Add("name", fullName);
        tag.Attributes.Add("value", value != null ? value.ToString() : string.Empty);
        return new MvcHtmlString(tag.ToString());
    }
}
+1

All Articles