How to stop view returning default value in ASP.NET MVC
I have a site running with ASP.NET MVC 1 and have encountered a bug where a bool in my model is being reset to default because the value is not used in the view.
The code for the Controller:
public ActionResult Edit(Guid id)
{
Service service = GetService(id);
if (service == null)
return View("NotFound");
return View(service);
}
when the view code had:
<label for="IsActive"> Is Active: </label>
<%= Html.TextBox("IsActive") %>
it was working fine however once it was deleted the isactive field was always returned as 开发者_开发问答false. I no longer want the isactive to be seen or modified from this view but removing it has caused the value to be lost, i have tried setting the value and not displaying it with
<% Html.TextBox("IsActive"); %>
but that still had it defaulting the value to false
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Service service)
{
//UpdateLogic
}
in the post method, regardless what IsActive had been before, the Service.IsActive is always false
basically i was just wondering how i could get the site to keep the value it was passed without displaying the text box in the view (have tried googled but failed to get the right combination of words for a decent result)
Can you add it as a Hidden on the page:
<%= Html.Hidden("IsActive"); %>
You can hide it as a Hidden field on the page:
<% Html.Hidden("IsActive"); %>
BUT!! it is not recommended to do that. since it is very easy to manipulate the value and you dont want that.
the best way is just to get the value from the DB.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Service service)
{
Service originalService = GetService(id);
UpdateModel(originalService, new string[] { "Field1thatyouwanttoupdate", "fieldname2" });
}
this way you update all fields that you want, but NOT the IsActive field.
As a quick solution you can use a hidden field instead of the textbox and store the value there.
In general, though, if you don't want to display or update the value, why send it to the view? Create a ViewModel with only the data you actually need in the view and post it back and forth.
Create it as a hidden value:
<input id="IsActive" type="hidden" value="true" />
精彩评论