如何将Id的值发送到视图

时间:2015-11-28 08:30:11

标签: c# model-view-controller

我想将Id的值 - 从Upsert(Id)发送到渲染的View,我正在努力。在我之前的问题中,有类似的方法正在起作用而这个方法不是。我觉得我在Model中做错了但我不知道是什么。 我哪里弄错了?这是我的控制器方法:

    [HttpGet]
    public ActionResult Upsert(int Id)
    {            
        return View();
    }


    [HttpPost]
    public ActionResult Upsert(UpsertViewModel upsertModel)
    {

        if (!ModelState.IsValid)
        {
            return View("Upsert", upsertModel);
        }

        if (!upsertModel.Address.Address_Id.HasValue   ||upsertModel.Address.Address_Id == 0)
        {
            _addressService.insertAddress(upsertModel.Address);
        }
        else
        {
            _addressService.updateAddress(upsertModel.Address);

        }

        return RedirectToAction("Index");
    }

这是我的模特:

namespace Clients.Models
{
public class UpsertViewModel
{
    public UpsertViewModel(AddressModel address)
    {

        Address = new AddressModel();
        Address.Id = address.Id;
        Address.Address_Id = address.Address_Id;
        Address.AddressLine_1 = address.AddressLine_1;
        Address.AddressLine_2 = address.AddressLine_2;
        Address.Postcode = address.Postcode;
        Address.Town = address.Town;
        Address.DateMovedIn = address.DateMovedIn;

    }
    public AddressModel Address { get; set; }
}

}

观点:

@model Clients.Models.UpsertViewModel
@using (Html.BeginForm(FormMethod.Post))
{
    @Html.ValidationSummary()
    @Html.HiddenFor(m=>m.Address.Id)<br/>
    @Html.HiddenFor(m => m.Address.Address_Id)<br />
    @Html.LabelFor(m => m.Address.AddressLine_1) @Html.TextBoxFor(m => m.Address.AddressLine_1)
    @Html.ValidationMessageFor(m => m.Address.AddressLine_1)<br />
    @Html.LabelFor(m => m.Address.AddressLine_2) @Html.TextBoxFor(m => m.Address.AddressLine_2)
    @Html.ValidationMessageFor(m => m.Address.AddressLine_2)<br />
    @Html.LabelFor(m => m.Address.Postcode) @Html.TextBoxFor(m => m.Address.Postcode)
    @Html.ValidationMessageFor(m => m.Address.Postcode)<br />
    @Html.LabelFor(m => m.Address.Town) @Html.TextBoxFor(m => m.Address.Town)
    @Html.ValidationMessageFor(m => m.Address.Town)<br />
    @Html.LabelFor(m => m.Address.DateMovedIn) @Html.TextBoxFor(m => m.Address.DateMovedIn)
    @Html.ValidationMessageFor(m => m.Address.DateMovedIn)<br />


    <input type="submit" value="OK"/>
}

1 个答案:

答案 0 :(得分:0)

除了您为批量分配漏洞打开应用程序之外,

这是你可以尝试做的事情:(这是一个猜测(没有VS安装测试),所以请耐心等待)

UpsertViewModel添加默认构造函数,然后重试。

根据您之前提到的问题和上面提到的代码片段,Id字段会传递到您的&#34; GET&#34;方法,因为UpsertViewModel在上一个问题中有一个Id属性,但现在它被包装在UpsertViewModel.Address中。 Model Binder通过Reflection

发挥其神奇作用

来自@StephenMuecke

要展开@ Aniket的评论,您的GET方法会有一个名为Id的参数,因此其值会添加到路径值中(请查看<form>元素的action属性)。当模型还具有参数名称Id时,在提交表单时该值将绑定到模型,因为除了表单值之外,DefaultModelBinder还会从路径参数(和查询字符串值)中读取值。在这种情况下,您的模型没有名为Id的属性(只有一个名为Address.Id)