【问题标题】:Model nested type is null when after modelbinding模型绑定后模型嵌套类型为空
【发布时间】:2013-12-24 07:31:50
【问题描述】:

我有一个 ViewModel 如下:

public class CheckoutViewModel
{
    public string ProductNumber { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public Input UserInput;

    public class Input
    {
        public string Email { get; set; }
        public string Phone { get; set; }
    }
}

还有这样的动作:

[HttpPost]
public ActionResult Index(CheckoutViewModel model)
{
    // ...
    return View();
}

我的模型绑定如下:

@model GameUp.WebUI.ViewModels.CheckoutViewModel

@using (Html.BeginForm("Index", "Checkout", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <!-- some HTML -->

    @Html.LabelFor(m => m.UserInput.Email)
    @Html.TextBoxFor(m => m.UserInput.Email)

    @Html.LabelFor(model => model.UserInput.Phone)
    @Html.TextBoxFor(model => model.UserInput.Phone)

    <button>Submit</button>
}

当我提交表单时,UserInput 为空。我知道 ASP.NET MVC 能够绑定嵌套类型,但在这段代码中不能。我也可以通过以下方式获取电子邮件和电话值:

var email = Request.Form["UserInput.Email"];
var phone = Request.Form["UserInput.Phone"];

也许我做错了什么!这是一个简单的模型绑定,您可以在网络上随处找到。

【问题讨论】:

  • 你能显示呈现的电子邮件或电话的 html 吗?
  • 将 UserInput 转换为 CheckoutViewModel 类中的属性
  • @SatpalSingh:是的,你是对的。我忘了让它成为财产。谢谢

标签: asp.net-mvc asp.net-mvc-4 model-binding


【解决方案1】:

你忘了在你的UserInput 里放一个setter,我不认为setter 是自动的。无论如何,您只需在您的 UserInput 中添加一个 getter/setter 即可使其工作,而无需在您的控制器方法中执行额外操作:

public Input UserInput { get; set; }

你的完整模型:

public class CheckoutViewModel
{
    public string ProductNumber { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public Input UserInput { get; set; }

    public class Input
    {
        public string Email { get; set; }
        public string Phone { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2011-04-25
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多