ASP MVC4 null模型传递给控制器​​中的操作

时间:2015-01-13 16:04:51

标签: c# asp.net-mvc-4

我想知道为什么我会将null模型从视图传递到控制器。

以下是我在视图中的代码(UpdatePersonal.cshtml):

@model Project.Models.UserInfo

@using (Html.BeginForm()){
   @Html.LabelFor(m => m.userinfo.firstname);
   @Html.TextBoxFor(m => m.userinfo.firstname, new { @Value = ViewBag.Firstname });

   @Html.LabelFor(m => m.userinfo.lastname);
   @Html.TextBoxFor(m => m.userinfo.lastname, new { @Value = ViewBag.Lastname });

   @Html.LabelFor(m => m.userinfo.email);
   @Html.TextBoxFor(m => m.userinfo.email, new { @Value = ViewBag.Email });

   @Html.LabelFor(m => m.userinfo.phone);
   @Html.TextBoxFor(m => m.userinfo.phone, new { @Value = ViewBag.Phone });

   @Html.HiddenFor(m => m.username, new { @Value = ViewBag.Username });

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

以下是接受它的操作方法:

[HttpPost]
[AllowAnonymous]
public ActionResult UpdatePersonal(UserInfo userInfo){
    //some code here
    //my breakpoint}

我看到传递的模型具有空值,因为我使用了断点

我的模特:

public class UserInfo
{
    [BsonId]
    public string username { get; set; }
    public Info userinfo { get; set; }
    public Address address { get; set; }


    public class Info
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
    }

    public class Address
    {
        public string street { get; set; }
        public string address1 { get; set; }
        public string address2 { get; set; }
        public string postalcode { get; set; }
        public string country { get; set; }
    }
}

2 个答案:

答案 0 :(得分:2)

您解决了这个问题,但是您的第一个代码很好,唯一的问题是您的操作方法参数的名称与您的模型属性的名称相同。

更改您的操作方法签名,例如:

public ActionResult UpdatePersonal(UserInfo info)

它应该可以工作!

答案 1 :(得分:0)

我刚刚解决了我的问题,而是使用并传递了子类

@model Buch_Ankauf.Models.UserInfo.Info

@using (Html.BeginForm()){

@Html.LabelFor(m => m.firstname);
@Html.TextBoxFor(m => m.firstname, new { @Value = ViewBag.Firstname });

@Html.LabelFor(m => m.lastname);
@Html.TextBoxFor(m => m.lastname, new { @Value = ViewBag.Lastname });

@Html.LabelFor(m => m.email);
@Html.TextBoxFor(m => m.email, new { @Value = ViewBag.Email });

@Html.LabelFor(m => m.phone);
@Html.TextBoxFor(m => m.phone, new { @Value = ViewBag.Phone });

@Html.Hidden("username", new { @Value = ViewBag.Username });

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

在我的控制器中:

    [HttpPost]
    [AllowAnonymous]
    public ActionResult UpdatePersonal(UserInfo.Info userInfo)
    {
相关问题