我开始并尝试遵循史蒂夫·桑德森的博客文章,但是它在MVC2中,我使用5,所以我可以在部分上使用动态CRUD。
我在@Html.RenderPartial("GiftEditorRow", item)上得到一个错误,声明表达式不向发件人返回值。
我哪里出问题了?当然,它很简单,但是想了解如何使用这个功能。
编号:索引:
@model IEnumerable<Project.Models.Gift>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Gift List</h2>
What do you want for your birthday?
@using (Html.BeginForm())
{
<div id="editorRows">
@foreach (var item in Model)
{
@Html.RenderPartial("GiftEditorRow", item)
}
</div>
@Html.ActionLink("Add another...", "BlankEditorRow", null, new {id = "addItem"});
<input type="submit" value="Finished" />
}
@section scripts {
<script type="text/javascript">
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
$("a.deleteRow").live("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
</script>
}部分:
@using HierarchicalControlsDemo.Helpers
<div class="editorRow">
@using (Html.BeginCollectionItem("gifts"))
{
Item: @Html.TextBoxFor(x => x.Name);
Value: @Html.TextBoxFor(x => x.Price, new { size = 4 });
<a href="#" class="deleteRow">delete</a>
}
</div>型号:
public class Gift
{
public string name { get; set; }
public double price { get; set; }
}主计长:
public class GiftController : Controller
{
// GET: Gift
public ActionResult Index()
{
var initialData = new[]
{
new Gift {name = "Tall Hat", price = 39.95},
new Gift {name = "Long Cloak", price = 120.00}
};
return View(initialData);
}
public ViewResult BlankEditorRow()
{
return View("GiftEditorRow", new Gift());
}
}发布于 2015-08-13 13:01:52
RenderPartial()返回void (它写入响应流),因此正确的用法是
@{ Html.RenderPartial(...); }另外,您需要使用返回一个Partial的string
@Html.Partial(...)附带注意:删除项的脚本将不适用于动态创建的元素,应该是
$('#editorRows').on('click', '.deleteRow', function() {
$(this).closest('.editorRow').remove();
});发布于 2015-08-14 10:11:14
您之所以在Stephen的答案的注释中看到这些错误,是因为您的部分中有一个意外的/不可读的代码。改为:
@using HierarchicalControlsDemo.Helpers
@model Project.Models.Gift
<div class="editorRow">
@using (Html.BeginCollectionItem("gifts"))
{
@Html.LabelFor(m =>m.name);
@Html.TextBoxFor(x => x.name);
@Html.LabelFor(m=>m.price);
@Html.TextBoxFor(x => x.price);
<a href="#" class="deleteRow">delete</a>
}
</div>https://stackoverflow.com/questions/31988600
复制相似问题