无法使用textboxfor将值从文本框传递到控制器

时间:2014-10-09 11:36:55

标签: c# asp.net-mvc textbox controller html.textboxfor

我尝试将值从文本框传递给控制器​​但是我的第一个值被传递而我的第二个值没有传递。简而言之,我会在这里发布我的代码:

索引视图中的代码:

@model FirstProject.Controllers.Family

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (@Html.BeginForm("SubmitTextBox", "OtherExample", FormMethod.Post))
{
    @Html.TextBoxFor(x => x.Name)
    @Html.TextBoxFor(x => x.Member.FirstName)
    <input type="submit"/>
}

<p>@Model.Name</p>
<p>@Model.Member.FirstName</p>

来自控制器的代码:

public ActionResult Index()
        {
            return View(new Family());
        }

        public ActionResult SubmitTextBox(Family model)
        {
            return View("Index", model);
        }

和我的模特:

public class Family
{
    public string Name { get; set; }
    public Member Member;
    public Family()
    {
        Member = new Member();
    }

}

public class Member
{
    public string FirstName { get; set; }
}

显示了我的名字值,但我的Member.Firstname未显示在视图中,因为未通过。发生了什么事可以解释一下吗?

1 个答案:

答案 0 :(得分:2)

您尚未Member 属性

在模型而不是字段中设置Member 属性

public Member Member {get;set;}

你的模特:

public class Family
{
    public string Name { get; set; }
    public Member Member {get;set;}
    public Family()
    {
        Member = new Member();
    }

}