创建Viewmodel以在mvc 4中发布数据和显示数据

时间:2016-03-08 06:27:00

标签: c# asp.net-mvc entity-framework

我正在创建一个表单。我有viewmodel。我有一个表单,我有client_id,Emp_id和提交按钮。点击提交按钮后,我想显示一些数据。这是我的观点模型。

public class GroupVM
{
    public string Name { get; set; }
    public IEnumerable<MyItem> Items { get; set; }
}
Public class MyItem
{
public string client_id {get;set;}
public string emp_id {get;set;}

public string Label { get; set; }
public string Value { get; set; }
public string Emp_id { get; set; }
public string Name { get; set; }
}

目前这是视图代码。

@model IEnumerable<GroupVM>
@foreach(var group in Model)
{
    <table>
        <thead>
            <tr>
                <th>Name</th>
                @foreach(var item in group.Items)
                {
                    <th>@item.Label</th>
                }
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>@group.Name</td>
                @foreach(var item in group.Items)
                {
                    <td>@item.Value</td>
                }
            </tr>
        </tbody>
    </table>
}

在此视图中,我想要client_id和emp_id的文本框。现在问题是如果我把@model IEnumerable放在视图头中我不能把文本框放到client_id和emp_id。那我应该改变我的viewmodel吗?当我点击提交按钮时,基于emp_id和client_id,我已经编写了查询来获取数据,它将绑定到模型。 这是我的控制器代码,用于将数据绑定到模型。

public ActionResult Test()
{
    var table = new List<MyItem> {
        new MyItem { Label = "DocumentNumber", Value = "12345678", Emp_id = 1, Name = "First" },
        new MyItem { Label = "ExpiryDate", Value = "1/1/2015", Emp_id = 1, Name = "First" },
        new MyItem { Label = "IssueLoc", Value = "India", Emp_id = 1, Name = "First" },
        new MyItem { Label = "DocumentNumber", Value = "SecondValue", Emp_id = 2, Name = "Second" },
        new MyItem { Label = "ExpiryDate", Value = "SecondValue", Emp_id = 2, Name = "Second" },                
    };
    var data = table.GroupBy(x => x.Name).Select(x => new GroupVM
    {
        Name = x.Key,
        Items = x
    });
    return View(data);
}

1 个答案:

答案 0 :(得分:1)

您需要另一个包含client_idemp_id属性以及GroupVM

集合的视图模型
public class SearchVM
{
    public string ClientID { get; set; }
    public string EmployeeID { get; set; }
    public IEnumerable<GroupVM> Groups { get; set; }
}

并在视图中

@model SearchVM
....
@using (Html.BeginForm("Test", "Home", FormMethod.Get))
{
    @Html.TextBoxFor(m => m.ClientID)
    @Html.TextBoxFor(m => m.EmployeeID)
    <input type="submit" value="Search" />
}
@foreach(var group in Model.Groups) // change
{
    .... // as before
}

并将Test()方法更改为

public ActionResult Test(string clientID, string employeeID)
{
    // filter your data based on the parameters, for example
    var data = table.Where(x => x.Emp_id == EmployeeID).GroupBy(x => x.Name).Select( ..... );
    SearchVM model = new SearchVM
    {
        ClientID = clientID,
        EmployeeID = employeeID,
        Groups = data
    };
    return View(model);
}

附注:使用文本框输入ID属性似乎不合适,您应该考虑使用下拉列表来呈现每个Employee的名称(但是回发ID值)。您还可以考虑使用ajax将值发布到控制器方法,该方法返回表的部分视图并更新DOM而不离开页面以提高性能。