mvc passing more than one parameters to partial view
I would like to pass more than one parameter to the partial view. With the following
<% Html.RenderPartial("Details", Model.test, new ViewDataDictionary { { "labelName", "Values1" }, {"header", "Header1"}, {"header2", "Header2"}}); %>
code, I am having error message
) missing.
What is wrong?
<%@ 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>
<%}
%>
<%} %>
<% } %>
Instead of using the ViewDataDictionary can't you simply add the required values to the model:
public class MyModel
{
public string Test { get; set; }
public string LabelName { get; set; }
public string Header { get; set; }
public string Header2 { get; set; }
}
and then simply:
<% Html.RenderPartial("Details", Model); %>
Other than that there's nothing wrong with your syntax. The error you are getting is from somewhere else:
<% Html.RenderPartial(
"Details",
Model.test,
new ViewDataDictionary {
{ "labelName", "Values1" },
{ "header", "Header1" },
{ "header2", "Header2" }
}
); %>
UPDATE:
Now that you've shown your code, let me suggest you a cleaner approach using editor templates.
Start by defining a model:
public class MyModel
{
public IEnumerable<Label> Labels { get; set; }
}
public class Label
{
public string ID { get; set; }
public string Name { get; set; }
}
Then a controller which will fill this model:
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);
}
}
Then the view (~/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>
and finally the editor template (~/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>
As you can see, using editor templates you no longer have to worry about naming the inputs, maintaining and incrementing indexes, writing loops, all those error prone things are handled by the framework automagically.
精彩评论