[asp.net-mvc] HTML.HiddenFor value set

@Html.HiddenFor(model => model.title, new { id= "natureOfVisitField", @value = '@Model.title'})

it doesen't work! how to set the value?

This question is related to asp.net-mvc asp.net-mvc-3 html-helper html.hiddenfor

The answer is


You can do this way

@Html.HiddenFor(model=>model.title, new {ng_init = string.Format("model.title='{0}'", Model.title) })

Necroing this question because I recently ran into the problem myself, when trying to add a related property to an existing entity. I just ended up making a nice extension method:

    public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, TProperty value)
    {
        string expressionText = ExpressionHelper.GetExpressionText(expression);
        string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);

        return htmlHelper.Hidden(propertyName, value);
    }

Use like so:

@Html.HiddenFor(m => m.RELATED_ID, Related.Id)

Note that this has a similar signature to the built-in HiddenFor, but uses generic typing, so if Value is of type System.Object, you'll actually be invoking the one built into the framework. Not sure why you'd be editing a property of type System.Object in your views though...


Strange but, Try with @Value , capital "V"

e.g. (working on MVC4)

@Html.HiddenFor(m => m.Id, new { @Value = Model.Id })

Update:

Found that @Value (capital V) is creating another attribute with "Value" along with "value", using small @value seems to be working too!

Need to check the MVC source code to find more.


Update, After going through how it works internally:

First of all forget all these workarounds (I have kept in for the sake of continuity here), now looks silly :)

Basically, it happens when a model is posted and the model is returned back to same page.

The value is accessed (and formed into html) in InputHelper method (InputExtensions.cs) using following code fragment

string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));

The GetModelStateValue method (in Htmlelper.cs) retrieves the value as

ViewData.ModelState.TryGetValue(key, out modelState)

Here is the issue, since the value is accessed from ViewData.ModelState dictionary. This returns the value posted from the page instead of modified value!!

i.e. If your posted value of the variable (e.g. Person.Id) is 0 but you set the value inside httpPost action (e.g. Person.Id = 2), the ModelState still retains the old value "0" and the attemptedValue contains "0" ! so the field in rendered page will contain "0" as value!!

Workaround if you are returning model to same page : Clear the item from ModelState,

e.g.

ModelState.Remove("Id"); 

This will remove the item from dictionary and the ViewData.ModelState.TryGetValue(key, out modelState) returns null, and the next statement (inside InputExtensions.cs) takes the actual value (valueParameter) passed to HiddenFor(m => m.Id)

this is done in the following line in InputExtensions.cs

tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);

Summary:

Clear the item in ModelState using:

ModelState.Remove("...");

Hope this is helpful.


For setting value in hidden field do in the following way:

@Html.HiddenFor(model => model.title, 
                new { id= "natureOfVisitField", Value = @Model.title})

It will work


It is just Value, not @value.. Try it. I'm not sure about @Model.title, maybe it's just Model.title


The @ symbol when specifying HtmlAttributes is used when the "thing" you are trying to set is a keyword c#. So for instance the word class, you cannot specify class, you must use @class.


Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to html-helper

How to add "required" attribute to mvc razor viewmodel text input editor URL.Action() including route values HTML.HiddenFor value set How to change the display name for LabelFor in razor in mvc3? Handling onchange event in HTML.DropDownList Razor MVC How to create a readonly textbox in ASP.NET MVC3 Razor Current date and time - Default in MVC razor How to remove the default link color of the html hyperlink 'a' tag? Set disable attribute based on a condition for Html.TextBoxFor ASP.NET MVC DropDownListFor with model of type List<string>

Examples related to html.hiddenfor

HTML.HiddenFor value set Html.HiddenFor value property not getting set What is the difference between Html.Hidden and Html.HiddenFor What does Html.HiddenFor do?