将视图模型的一部分传递给控制器

时间:2013-08-15 21:35:53

标签: c# asp.net-mvc view model controller

我有一个Customer索引页面,它使CustomerIndexViewModel用一个客户列表,请求所花费的时间以及许多其他信息来填充页面。

我在CustomerIndexViewModel中有一个CustomerSearchArgsModel。

public class CustomerIndexViewModel : BaseIndexViewModel
{
    public IEnumerable<Customer> Customers{ get; set; }
    public double RequestTime { get; set; }
    public CustomerSearchArgsModel CustomerSearchArgsModel { get; set; }
    public OtherTypes OtherType {get;set;}
}


public class CustomerSearchArgsModel
{
    public string CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

在我的客户索引页面上,我希望有类似的内容 -

@model CustomerIndexViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("Index","Customer",FormMethod.Post, new { id="searchSubmit"}))
{
    @Html.LabelFor(model => model.CustomerSearchArgsModel.ConsumerID)
    @Html.EditorFor(model => model.CustomerSearchArgsModel.ConsumerID)
    @Html.LabelFor(model => model.CustomerSearchArgsModel.LastName)
    @Html.EditorFor(model => model.CustomerSearchArgsModel.LastName)
    @Html.LabelFor(model => model.CustomerSearchArgsModel.FirstName)
    @Html.EditorFor(model => model.CustomerSearchArgsModel.FirstName)

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

我想将输入的值返回到CustomerSearchArgsModel中Customer控制器上的Index(POST)方法。

但我不知道如何返回与页面顶部定义的模型不同的模型。

1 个答案:

答案 0 :(得分:2)

您可以将“searchSubmit”表单放在局部视图中。然后将 model.CustomerSearchArgsModel 传递给局部视图。确保 model.CustomerSearchArgsModel 不为null;否则,你会得到一个例外。

索引页

@Html.Partial("_search", model.CustomerSearchArgsModel)

_search Partial View

@model CustomerSearchArgsModel
@using (Html.BeginForm("Index","Customer",FormMethod.Post, new { id="searchSubmit"}))
{
    @Html.LabelFor(model => model.ConsumerID)
    @Html.EditorFor(model => model.ConsumerID)
    @Html.LabelFor(model => model.LastName)
    @Html.EditorFor(model => model.LastName)
    @Html.LabelFor(model => model.FirstName)
    @Html.EditorFor(model => model.FirstName)

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

此方法的问题是您将在ConsumerBox的文本框中显示0值。要解决此问题,您可以使用Html.Action而不是Html.Partial。

希望这有帮助。