模型绑定不适用于复杂对象

时间:2016-05-01 14:59:36

标签: asp.net-mvc model-binding

以下是我要发布的观点:

@model WelcomeViewModel
@using (Html.BeginForm("SignUp", "Member", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{

    ....
    <div class="form-group">
        @Html.EditorFor(model => model.SignUp.CompanyName, new {htmlAttributes = new {@class = "form-control" }})
    </div>
    <div class="form-group">
        @Html.EditorFor(model => model.SignUp.RegisteredNo, new {htmlAttributes = new {@class = "form-control" } })
    </div>
    ....
    <button type="submit" name="signup" class="btn">Register</button>
}

视图模型:

public class WelcomeViewModel
{
    public SignInViewModel LogOn { get; set; }
    public SignUpViewModel SignUp { get; set; } 
}

行动方法:

[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public virtual async Task<ActionResult> SignUp(SignUpViewModel model)
{
    if (!ModelState.IsValid)
        return View("SignIn", new WelcomeViewModel { SignUp = model });

    // other code
    return View();
}

当我发布数据时,模型变为空。我知道输入将生成如下:

<input id="SignUp_CompanyName" name="SignUp.CompanyName">

但是模型绑定器接受了这个:

<input id="SignUp_CompanyName" name="CompanyName">

现在我想知道如何删除该前缀?我知道我可以为每个输入明确添加名称:

@Html.TextBoxFor(model => model.SignUp.CompanyName, new { Name = "CompanyName" })

但我想以强烈的方式做到这一点。

1 个答案:

答案 0 :(得分:0)

最简单的方法可能是将[Bind]属性设置为“{1}”设置为“SignUp”:

Prefix

请参阅MSDN