【问题标题】:Passing part of a viewmodel to a controller将视图模型的一部分传递给控制器
【发布时间】:2013-08-15 21:35:52
【问题描述】:

我有一个客户索引页面,它采用 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) 方法。

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

【问题讨论】:

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


    【解决方案1】:

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

    索引页面

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

    _搜索部分视图

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

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

    希望这会有所帮助。

    【讨论】:

    • 谢谢,整理好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多