简体   繁体   中英

Value doesn't appear filled in the View

I have a strange problem here.

In the Model (.cs):

    public long? ContactoAdditionalId { get; set; }
    public long Test1 { get; set; }
    public long? Test2 { get; set; }
    public string Test3 { get; set; }

In the Controller (at the end of the action just before the view):

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Index( Contacto model )
    {
        DoSomeStuff( model, ... );

        (...)

        model.Test1 = model.ContactoAdditionalId.HasValue ? model.ContactoAdditionalId.Value : -1;
        model.Test2 = model.ContactoAdditionalId;
        model.Test3 = model.ContactoAdditionalId.HasValue ? model.ContactoAdditionalId.Value.ToString() : "No value!";
        return View( model );
    }

Finally in the View (.cshtml):

@using MyApp.Models;

@model Contacto

@using ( Html.BeginForm( "Index", "Contacto" ) )
{
    @Html.HiddenFor( model => model.ContactoAdditionalId )
    @Html.HiddenFor( model => model.Test1 )
    @Html.HiddenFor( model => model.Test2 )
    @Html.HiddenFor( model => model.Test3 )
    (...)

As you may have guessed, the ContactoAdditionalId (I left it with the real name, in case THAT is the problem) value is NOT appearing in the View.

When I press F12 in Chrome to open the Developer Tools and inspect the HTML, there is no value for the ContactoAdditionalId , but there ARE values for Test1, Test2 and Test3.

Note that I used a long, a long? and a string to check if the problem was something to do with the types, but all three show value in the HTML.

Of course, the purpose of this hidden field is to get that ContactoAdditionalId back when POST'ing. This way it doesn't work and its model property is null!

I also noticed something strange: if I add in the View, just before the HiddenFor:

@Html.DisplayFor( model => model.ContactoAdditionalId, ... )

It suddenly works and now the hidden field has the value in it!

What is happening here? I ran debug step-to-step in Visual Studio 2017 and when I reached the end of the action code, it started stepping in the cshtml View, so no additional code (as far as I know, at least not our project's code) is being executed after the action and before the view is transformed in HTML.

You probably have a parameter in ModelState with the same name than the one you don't see the data. If you are changing that value in the Model, without clearing it from the ModelState, HiddenFor will pick the ModelState field first. Either do a ModelState.Clear(), or remove only the field with ModelState.Remove( "ContactoAdditionalId" )"

Also, you can use ModelState.Clear().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM