0

Hi I have the following Action method in my Controller class:

[HttpPost]
public IActionResult MyAction(string foo, Guid? bar)
{
    if(!bar.hasValue)
        bar = Guid.NewGuid();
    var viewModel = new MyViewModel { Foo = foo, Bar = bar };
    return ViewComponent("MyDialog", new {model = viewModel});
}

And my view component is:

@model MyViewModel
<div>
    @Html.HiddenFor(m => m.Bar)
    <span>@Model.Bar</span>
</div>

This was fine when bar has value during calling MyAction(), if bar is null then the value of the hidden tag generated does not set to Guid.NewGuid(). However the <span> tag can always display the correct value from the ViewModel passed.

Why?

MasterWil
  • 891
  • 8
  • 24
  • 1
    Because the values have been added to `ModelState` in the POST method. You can use `ModelState.Clear()` before updating the property (or change the name of the parameters so they do not match the model properties) –  Nov 29 '16 at 09:07
  • @StephenMuecke Thank you! May you post it as an answer so I can mark it? – MasterWil Nov 29 '16 at 09:16
  • 1
    Marked it as a dupe instead :) –  Nov 29 '16 at 09:20

0 Answers0