将viewModel的一部分发布到post action方法

时间:2017-07-21 07:44:41

标签: c# asp.net-mvc

我想知道我是做错了什么,或者不可能只使用默认模型绑定器发布部分视图模型。让我们说我有一个复杂的视图模型,只有一小部分应该发布。我想实现这样的目标:

public class ComplexViewModel
{
    public object FirstNotPostedData { get; set; }
    public object SecondNotPostedData { get; set; }
    //......
    public object NthNotPostedData { get; set; }

    public InnerModelToPost InnerModelToPost { get; set; }
}

public class InnerModelToPost
{
    public string FirstProperty { get; set; }
    public string SecondProperty { get; set; }
    public string ThirdProperty { get; set; }
}

在视图中我想显示模型的一部分并发布其他部分:

@model ComplexViewModel
@* DISPLAYING DATA *@
<form>
    @Html.HiddenFor( m => m.InnerModelToPost.FirstProperty )
    @Html.HiddenFor( m => m.InnerModelToPost.SecondProperty )
    @Html.HiddenFor( m => m.InnerModelToPost.ThirdProperty )

    <button type="submit">Submit button</button>
</form>

然后我希望能够使用默认模型绑定器以这种方式将此模型传递给我的控制器:

public ActionResult GetOnlyImportantPartOfModel( InnerModelToPost innermodel)
{
    //I'm getting empty model when I' doing like this

    return View();
}

您可能会问为什么不将整个模型作为参数传递给此操作方法。所以答案是:代码可读性。我将ComplexViewModel存储在会话中,并在我的action方法的第一行中读取它。我想只传递我想用。更新我的模型的数据。

1 个答案:

答案 0 :(得分:3)

您需要使用Prefix属性的[Bind]属性从表单值中删除InnerModelToPost前缀。

public ActionResult GetOnlyImportantPartOfModel([Bind(Prefix = "InnerModelToPost")] InnerModelToPost innermodel)
{
    ....
}

话虽如此,如果您只使用InnerModelToPost的属性,那么在您的GET方法中,您可以从ComplexViewModel读取父类(Session),但只传递{视图的{1}}属性