如何将Id的值发送到视图

本文关键字:视图 Id | 更新日期: 2023-09-27 18:25:01

我想将Id的值从Upsert(Id)发送到渲染视图,但我很难。在我之前的问题中,有一种类似的方法在起作用,而这个方法不起作用。我想我在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"/>
}

如何将Id的值发送到视图

除了您正在打开应用程序以应对批量分配漏洞之外,

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

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

根据您之前的问题和上面提到的代码片段,Id字段被传递到您的"GET"方法中,因为UpsertViewModel在之前的问题中有一个Id属性,但现在它被封装在UpsertView Model.Address中。模型绑定器正通过反射发挥其魔力

作者:StephenMuecke

为了扩展@Aniket的注释,您的GET方法有一个名为Id的参数,因此它的值将添加到路由值中(查看<form>元素的action属性)。如果您的模型也有参数名称Id,则在提交表单时,该值将绑定到您的模型,因为DefaultModelBinder除了读取表单值外,还读取路由参数(和查询字符串值)中的值。在这种情况下,您的模型没有名为Id的属性(只有一个名为Address.Id)