返回一个 List<E>从视图模型中的视图 [英] Return a List&lt;E&gt; from a view in view model

查看:18
本文介绍了返回一个 List<E>从视图模型中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况:

我有这个视图模型:

公共类ViewModel{公共日期时间 someDate { 获取;放;}公共字符串 someString { 获取;放;}公共列表<E>someList { 获取;放;}}

我要做的是在视图中设置日期,写一些文本,然后从 E 的列表中选择任意数量的 E.动作中返回的 ViewModel 必须有日期、文本和包含的列表所选项目.

我需要知道的是如何处理上述列表.如何将每个选定的项目添加到模型的列表中.我正在考虑将属性 public bool selected 添加到 E,然后发送所有项目并过滤服务器上选定的项目,但是我不想来回发送所有数据,因为列表可以相当大.

我将 MVC3 与 razor 和 JQUERY AJAX 用于我的所有表单帖子.

如果我没有说清楚,请告诉我.

谢谢.

解决方案

这是您可以用来实现此目的的一种技术.

让我们从视图模型开始:

公共类ViewModel{公共日期时间 SomeDate { 获取;放;}公共字符串 SomeString { 获取;放;}公共列表<E>SomeList { 获取;放;}}公开课E{公共布尔选择{得到;放;}公共字符串 Foo { 获取;放;}公共字符串栏 { 获取;放;}}

然后我们编写一些控制器来处理视图的渲染和 AJAX 请求:

公共类 HomeController : 控制器{公共 ActionResult 索引(){var 模型 = 新的 ViewModel{SomeDate = DateTime.Now,SomeString = "一些文字",SomeList = Enumerable.Range(1, 7).Select(x => new E{foo = "foo" + x,条 = "条" + x}).ToList()};返回视图(模型);}[HttpPost]公共 ActionResult 索引(ViewModel 模型){//在这里,我们将正确绑定我们的视图模型并//列表将只包含用户的项目//已选择(见下文...)//TODO: 做一些处理return Content("感谢您提交此数据", "text/plain");}}

然后我们转到 ~/Views/Home/Index.cshtml 视图:

@model ViewModel@using (Html.BeginForm()){<div>@Html.LabelFor(x => x.SomeDate)@Html.EditorFor(x => x.SomeDate)

<div>@Html.LabelFor(x => x.SomeString)@Html.EditorFor(x => x.SomeString)

<表格><头><tr><th></th><th>Foo</th><th>Bar</th></tr></thead>@Html.EditorFor(x => x.SomeList)</tbody><input type="submit" value="使用 AJAX 将选定的值发送到服务器"/>}

最后,我们为 E 类型 (~/Views/Home/EditorTemplates/E.cshtml) 定义了一个编辑器模板,它将为每个元素呈现合集:

@{var index = Guid.NewGuid().ToString();var prefix = Regex.Replace(ViewData.TemplateInfo.HtmlFieldPrefix, @"[d+]$", match =>{return string.Format("[{0}]", index);});ViewData.TemplateInfo.HtmlFieldPrefix = 前缀;}<input type="hidden" name="SomeList.Index" value="@index"/><tr><td>@Html.DisplayFor(x => x.Foo)@Html.HiddenFor(x => x.Foo)</td><td>@Html.DisplayFor(x => x.Bar)@Html.HiddenFor(x => x.Bar)</td><td>@Html.CheckBoxFor(x => x.Selected)</td></tr>

好的,所以在这个阶段我们还没有编写 javascript 部分,所以它应该表现得像一个普通的 HTML 表单,当它被提交时,它会将所有值发送到服务器.

最后一部分是对表单进行 AJAX 化并仅 POST 用户在请求中选择的记录.所以我们可以在一个单独的 javascript 文件中做到这一点:

$(function () {$('form').submit(function () {//我们克隆原始表单,我们将//过滤掉未选中的字段var myForm = $(this).clone(false, false);$('tr', myForm).each(function () {var isSelected = $(':checkbox', this).is(':checked');如果 (!isSelected) {$(this).remove();}});$.ajax({网址:this.action,类型:this.method,数据:myForm.serialize(),成功:功能(结果){警报(结果);}});返回假;});});

作为处理动态列表的好文章,我向您推荐 关注博文.

This is my situation:

I have this view model:

public class ViewModel
{
   public DateTime someDate { get; set; }
   public String someString { get; set; }
   public List<E> someList { get; set; }
}

What I have to do is in the view set the date, write some text and then select from a list of E any number of E. The ViewModel returned in the action must have the date, the text and contain the list of selected items.

What I need to know is how to handle said list. How can I add each selected item to the models' List. I was thinking on adding a property public bool selected to E and then send all items and filter the selected ones on the server, however I would rather not send back and forth all that data since the list can be quite large.

I am using MVC3 with razor and JQUERY AJAX for all my form posts.

If I am not making myself clear, please let me know.

Thank you.

解决方案

Here's one technique that you could use to achieve this.

Let's start with the view model:

public class ViewModel
{
    public DateTime SomeDate { get; set; }
    public string SomeString { get; set; }
    public List<E> SomeList { get; set; }
}

public class E
{
    public bool Selected { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}

then we write some controller to handle the rendering of the view and the AJAX request:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ViewModel
        {
            SomeDate = DateTime.Now,
            SomeString = "some text",
            SomeList = Enumerable.Range(1, 7).Select(x => new E
            {
                Foo = "foo " + x,
                Bar = "bar " + x
            }).ToList()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(ViewModel model)
    {
        // Here we will get our view model properly bound and 
        // the list will contain only the items that the user
        // has selected (see below...)

        // TODO: do some processing

        return Content("Thanks for submitting this data", "text/plain");
    }
}

then we move on to the ~/Views/Home/Index.cshtml view:

@model ViewModel

@using (Html.BeginForm()) 
{
    <div>
        @Html.LabelFor(x => x.SomeDate)
        @Html.EditorFor(x => x.SomeDate)
    </div>

    <div>
        @Html.LabelFor(x => x.SomeString)
        @Html.EditorFor(x => x.SomeString)
    </div>

    <table>
        <thead>
            <tr>
                <th></th>
                <th>Foo</th>
                <th>Bar</th>
            </tr>
        </thead>
        <tbody>
            @Html.EditorFor(x => x.SomeList)
        </tbody>
    </table>

    <input type="submit" value="Send selected values to server using AJAX" />
}

and finally we define an Editor template for the E type (~/Views/Home/EditorTemplates/E.cshtml) which will be rendered for each element of the collection:

@{
    var index = Guid.NewGuid().ToString();
    var prefix = Regex.Replace(ViewData.TemplateInfo.HtmlFieldPrefix, @"[d+]$", match =>
    {
        return string.Format("[{0}]", index);
    });
    ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}
<input type="hidden" name="SomeList.Index" value="@index" />
<tr>
    <td>
        @Html.DisplayFor(x => x.Foo)
        @Html.HiddenFor(x => x.Foo)
    </td>
    <td>
        @Html.DisplayFor(x => x.Bar)
        @Html.HiddenFor(x => x.Bar)
    </td>
    <td>
        @Html.CheckBoxFor(x => x.Selected)
    </td>
</tr>

OK, so at this stage we haven't yet written the javascript part so this should behave as a normal HTML form and when it is submitted it will send all the values to the server.

And final piece would be to AJAXify the form and POST only the records that the user selected in the request. So we could do this in a separate javascript file:

$(function () {
    $('form').submit(function () {
        // we clone the original form and we will
        // filter out the non-selected fields
        var myForm = $(this).clone(false, false);

        $('tr', myForm).each(function () {
            var isSelected = $(':checkbox', this).is(':checked');
            if (!isSelected) {
                $(this).remove();
            }
        });

        $.ajax({
            url: this.action,
            type: this.method,
            data: myForm.serialize(),
            success: function (result) {
                alert(result);
            }
        });

        return false;
    });
});

As a good article for handling dynamic lists I would recommend you the following blog post.

这篇关于返回一个 List<E>从视图模型中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆