How value of id goes from action method to the view

梦想与她 提交于 2019-12-11 20:14:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!