这是我的情况:
我有这个视图模型:
public class ViewModel
{
public DateTime someDate { get; set; }
public String someString { get; set; }
public List<E> someList { get; set; }
}
我要做的是在视图中设置日期,写一些文本然后从E列表中选择任意数量的E.在动作中返回的ViewModel必须具有日期,文本并包含列表选定的项目。
我需要知道的是如何处理所述列表。如何将每个选定的项目添加到模型的列表中。我正在考虑向E添加属性public bool selected
然后发送所有项目并过滤服务器上的所选项目,但是我不愿意来回发送所有数据,因为列表可能非常大。
我正在使用带有剃刀和JQUERY AJAX的MVC3来填写所有表单帖子。
如果我不清楚,请告诉我。
谢谢。
答案 0 :(得分:6)
这是您可以用来实现这一目标的一种技术。
让我们从视图模型开始:
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; }
}
然后我们编写一些控制器来处理视图和AJAX请求的呈现:
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");
}
}
然后我们转到~/Views/Home/Index.cshtml
视图:
@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" />
}
最后我们为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 = 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>
好的,所以在这个阶段我们还没有编写javascript部分,所以这应该像普通的HTML表单一样,当它被提交时,它会将所有的值发送到服务器。
最后一部分是AJAXify表单,POST只发送用户在请求中选择的记录。所以我们可以在一个单独的javascript文件中执行此操作:
$(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;
});
});
作为处理动态列表的好文章,我建议您使用following blog post。