如何将parameter passing给mvc 4中的局部视图
我有这样的链接:
<a href='Member/MemberHome/Profile/Id'><span>Profile</span></a> 当我点击它时,会调用这个部分页面:
  @{ switch ((string)ViewBag.Details) { case "Profile": { @Html.Partial("_Profile"); break; } } } 
部分页面_Profile包含:
 Html.Action("Action", "Controller", model.Paramter) 
例:
 @Html.Action("MemberProfile", "Member", new { id=1 }) // id is always changing 
我的疑问是,如何将这个“ID”传递给model.parameter部分 ?
我的控制器是:
  public ActionResult MemberHome(string id) { ViewBag.Details = id; return View(); } public ActionResult MemberProfile(int id = 0) { MemberData md = new Member().GetMemberProfile(id); return PartialView("_ProfilePage",md); } 
	
你的问题很难理解,但是如果我得到了主要观点,你只是在你的主视图中有一些价值,你想访问在该视图中呈现的部分。
如果只是用部分名称渲染一个部分:
 @Html.Partial("_SomePartial") 
它实际上会将你的模型作为一个隐式parameter passing,就像你打电话一样:
 @Html.Partial("_SomePartial", Model) 
现在,为了让你实际上能够使用它,它也需要有一个定义的模型,例如:
 @model Namespace.To.Your.Model @Html.Action("MemberProfile", "Member", new { id = Model.Id }) 
 另外,如果你正在处理一个不在视图模型中的值(它在ViewBag中,或者在视图本身中产生一个值,那么你可以传递一个ViewDataDictionary 
 @Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } }); 
接着:
 @Html.Action("MemberProfile", "Member", new { id = ViewData["id"] }) 
 和模型一样,Razor默认会隐式地传递视图的ViewData ,所以如果在视图中有ViewBag.Id ,那么你可以在你的视图中引用相同的东西。 
这是一个将对象转换为ViewDataDictionary的扩展方法。
 public static ViewDataDictionary ToViewDataDictionary(this object values) { var dictionary = new ViewDataDictionary(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values)) { dictionary.Add(property.Name, property.GetValue(values)); } return dictionary; } 
然后你可以在你的视图中使用它:
 @Html.Partial("_MyPartial", new { Property1 = "Value1", Property2 = "Value2" }.ToViewDataDictionary()) 
 这比new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }}语法好得多。 
 然后在你的局部视图中,你可以使用ViewBag来访问dynamic对象的属性而不是索引属性,例如 
 <p>@ViewBag.Property1</p> <p>@ViewBag.Property2</p> 
在我寻找自己的时候,我发现了单值的最短的方法之一,就是像这样在视图中传递单个string和设置string作为模型。
在您的部分呼叫方面
 @Html.Partial("ParitalAction", "String data to pass to partial") 
然后像这样用Partial View绑定模型
 @model string 
并在部分视图中使用它的值
 @Model 
你也可以使用像array,int这样的其他数据types或者更复杂的数据types,如IDictionary或其他types。
希望能帮助到你,
- ASP.NET MVC剃刀渲染没有编码
- 如何在razor中指定数据属性,例如@ this.Html.CheckBoxFor(…)上的data-externalid =“23151”
- ASP.NET MVC 3(Razor)Ajax.ActionLink – 我做错了什么?
- 在ASP.NET MVC中:从Razor视图调用Controller Action Method的所有可能的方法
- 如何创build自定义validation属性?
- 如何将IEnumerable列表传递给控制器在MVC包括checkbox状态?
- 如何使用AJAX呈现部分表单元素
- 使用Razor View Engine从ASP.NET MVC 3的局部视图中将内容注入特定的部分
- 动作图像MVC3剃刀