我想将多个参数传递给局部视图。有了以下
<% Html.RenderPartial("Details", Model.test, new ViewDataDictionary { { "labelName", "Values1" }, {"header", "Header1"}, {"header2", "Header2"}}); %>
代码,我有错误消息
)失踪。
有什么问题?
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MvcUI.Models.Label>>" %>
<%var label = ViewData["labelName"];%>
<%int count = 0; %>
<%if (Model!=null) {%>
<% foreach (var model in Model){ %>
<%if (!String.IsNullOrEmpty(model.Name))
{%>
<li>
<%: Html.Hidden((label)+".Index", count.ToString())%>
<%: Html.TextBox((label)+"[" + (count) + "].Name", model.Name, new { Style = "width:280px" })%>
<%: Html.Hidden((label)+"[" + (count++) + "].ID", model.ID, new { Style = "width:280px" })%>
<input type="button" value = "Delete"/>
</li>
<%}
%>
<%} %>
<% } %>
答案 0 :(得分:6)
您无需简单地将所需的值添加到模型中,而不是使用ViewDataDictionary:
public class MyModel
{
public string Test { get; set; }
public string LabelName { get; set; }
public string Header { get; set; }
public string Header2 { get; set; }
}
然后简单地说:
<% Html.RenderPartial("Details", Model); %>
除此之外,你的语法没有任何问题。你得到的错误来自其他地方:
<% Html.RenderPartial(
"Details",
Model.test,
new ViewDataDictionary {
{ "labelName", "Values1" },
{ "header", "Header1" },
{ "header2", "Header2" }
}
); %>
更新:
现在您已经展示了代码,让我建议您使用编辑器模板更清晰的方法。
首先定义一个模型:
public class MyModel
{
public IEnumerable<Label> Labels { get; set; }
}
public class Label
{
public string ID { get; set; }
public string Name { get; set; }
}
然后是一个将填充此模型的控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
Labels = new[]
{
new Label { ID = "l1", Name = "Label 1" },
new Label { ID = "l2", Name = "Label 2" },
new Label { ID = "l3", Name = "Label 3" }
}
};
return View(model);
}
}
然后是视图(~/Views/Home/Index.aspx
):
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SomeNs.Models.MyModel>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<ul>
<%: Html.EditorFor(x => x.Labels) %>
</ul>
</asp:Content>
最后是编辑器模板(~/Views/Home/EditorTemplates/Label.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.Models.Label>" %>
<li>
<%: Html.HiddenFor(x => x.ID) %>
<%: Html.TextBoxFor(x => x.Name) %>
<input type="button" value="Delete" />
</li>
正如您所看到的,使用编辑器模板,您不再需要担心命名输入,维护和增加索引,编写循环,所有这些容易出错的事情都由框架自动处理。