问题
I have a method AddAddress(int Id)
and I cannot work out how the value of Id goes to the View (when I check view source
of the rendered view the value is there).
I have to create more complicated but similar method and i just don't get how the value of Id
goes to the rendered View. I just need to know how it happens. Many thanks
AddAddress Method :
[HttpGet]
public ActionResult AddAddress (int Id)
{
return View();
}
[HttpPost]
public IActionResult AddAddress(AddressModel address)
{
if (!ModelState.IsValid)
{
return View("AddAddress", address);
}
if (!address.Address_Id.HasValue|| address.Address_Id == 0)
{
_addressService.insertAddress(address);
}
else
{
_addressService.updateAddress(address);
}
return RedirectToAction("Index");
}
the view that receives Id:
@model Clients.Models.AddressModel
@using (Html.BeginForm(FormMethod.Post))
{
@Html.ValidationSummary()
@Html.HiddenFor(m => m.Id)<br />
@Html.HiddenFor(m => m.Address_Id)<br />
@Html.LabelFor(m => m.AddressLine_1)
@Html.TextBoxFor(m => m.AddressLine_1)
@Html.ValidationMessageFor(m => m.AddressLine_1)<br />
@Html.LabelFor(m => m.AddressLine_2)
@Html.TextBoxFor(m => m.AddressLine_2)
@Html.ValidationMessageFor(m => m.AddressLine_2)<br />
@Html.LabelFor(m => m.Postcode)
@Html.TextBoxFor(m => m.Postcode)
@Html.ValidationMessageFor(m => m.Postcode)<br />
@Html.LabelFor(m => m.Town)
@Html.TextBoxFor(m => m.Town)
@Html.ValidationMessageFor(m => m.Town)<br />
@Html.LabelFor(m => m.DateMovedIn)
@Html.TextBoxFor(m => m.DateMovedIn)
@Html.ValidationMessageFor(m => m.DateMovedIn)<br />
<input type="submit" value="OK"/>
}
回答1:
Your razor view is strongly typed to AddressModel
class. So in your GET action method, create an object of AddressModel
class, set the Id
property value to whatever value came to your action method as parameter and send this object to the view.
[HttpGet]
public ActionResult AddAddress (int Id)
{
var model = new AddressModel();
model.Id = id;
return View(model);
}
You need to explicitly pass data to your view from your action method. There is no other magic way to do that. If you do not do that, It will still have the default value of integer type properties, which is 0.
来源:https://stackoverflow.com/questions/33968192/how-value-of-id-goes-from-action-method-to-the-view