MrPixel6
MrPixel6

Reputation: 377

ASP.NET MVC Hidden values modified by default

I'm currently working on a website in asp.net MVC. I have one view to edit my model but some item in this model can only be modified by admins.

So I removed some editorfor() for the basic users and everything works fine...
Until I saw that : if basic user edit the model, the fields which are hidden for them are modified to a default value not the previous one modified by an admin.

Did someone know how can I saved the previous values even they are not in an editorfor() ?

Code :

@Html.EditorFor(model => model.name) 
@if (ViewBag.Role == "Admin")
{
  @Html.EditorFor(model => model.age)  
  // If admin is connected, he can edit age => no problem
}
// if a user modify name but don't touch age because it's for admin only, the model age will get 0

Thanks in advance

Upvotes: 0

Views: 93

Answers (2)

Nirav Patel
Nirav Patel

Reputation: 520

@Html.EditorFor(model => model.name) 
@if (ViewBag.Role == "Admin")
{
  @Html.EditorFor(model => model.age)  
  // If admin is connected, he can edit age => no problem
}

If we take your example then age is only for admin. so when basic user will edit this page that time condition will not satisfied and @Html.EditorFor(model => model.age) will be not rendered for basic user. So when you post the form that time age's value will not be pass to controller because age is not rendered in form. so it will save default value which you set. Solution is you have to use hidden field out side the if condition. so value will be keep as it is controller -> View -> controller.

Upvotes: 1

MrPixel6
MrPixel6

Reputation: 377

@Html.HiddenFor(m = m.age)

Simple Answer for my stupid question, I have tried it on first but it didn't work but now it did so there is the solution. Thanks to Stephen Muecke.

Upvotes: 1

Related Questions