【问题标题】:Model binding doesn't work for complex object模型绑定不适用于复杂对象
【发布时间】:2016-05-01 14:59:35
【问题描述】:

这是我要发布的视图:

@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" })

但我想以强类型的方式来做。

【问题讨论】:

  • 根据haim770的回答使用[Bind]属性或回发WelcomeViewModel(不是SignUpViewModel

标签: asp.net-mvc model-binding


【解决方案1】:

也许最简单的方法是应用 [Bind] 属性并将其 Prefix 设置为“SignUp”:

public async Task<ActionResult> SignUp([Bind(Prefix="SignUp")] SignUpViewModel model)

MSDN

【讨论】:

    猜你喜欢
    • 2015-08-30
    • 2018-06-19
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2015-03-28
    相关资源
    最近更新 更多