我有一个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能够绑定嵌套类型,但在此代码中不能。我还可以通过以下方式获取Email和Phone值:
var email = Request.Form["UserInput.Email"];
var phone = Request.Form["UserInput.Phone"];
也许我做错了什么!这是一个简单的模型绑定,在网络上随处可见。
你忘了在你的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; }
}
}