asp.net-mvc 将参数传递给我的局部视图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1909134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing parameters to my partial view?
提问by mrblah
I am calling my partial view like this:
我这样称呼我的部分观点:
<% Html.RenderPartial("~/controls/users.ascx"); %>
Can I pass parameters to partial view? How will I access them in the actual users.ascx page?
我可以将参数传递给局部视图吗?我将如何在实际的 users.ascx 页面中访问它们?
采纳答案by Darin Dimitrov
You could pass a model object to the partial (for example a list of strings):
您可以将模型对象传递给部分(例如字符串列表):
<% Html.RenderPartial("~/controls/users.ascx", new string[] { "foo", "bar" }); %>
Then you strongly type the partial and the Modelproperty will be of the appropriate type:
然后你强类型的部分和Model属性将是适当的类型:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IEnumerable<string>>" %>
<% foreach (var item in Model) { %>
<div><%= Html.Encode(item) %></div>
<% } %>
回答by John Farrell
There is another overload for RenderPartial that will pass your model through.
RenderPartial 的另一个重载将传递您的模型。
<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>
How to access? Just like you normally would with any view:
如何访问?就像您通常对待任何视图一样:
<%= Model.MagicSauce %>
回答by Jules Bartow
It took a while to sink in, but MVC means you use a Model, a View, and a Controller one way or another for just about everything, including Partial Views. How all three elements fit together can be a little intimidating at first. I'd never done one until just now, and it works --Woohoo!
花了一段时间才理解,但 MVC 意味着您可以以一种或另一种方式使用模型、视图和控制器来处理几乎所有事情,包括部分视图。一开始,这三个元素如何组合在一起可能有点令人生畏。直到现在我才做过一个,它有效--哇!
Hope this helps the next person.... Sorry, I'm using razor instead of .Net forms. I'm also pulling data from a SQL Server database into Entity Framework, which a developer is likely to use. I also probably went a little overboard with WebGrid, which is so much more elegant than a foreach statement. A basic @webgrid.GetHtml() will display every column and row.
希望这能帮助下一个人.... 抱歉,我正在使用剃刀而不是 .Net 表单。我还将数据从 SQL Server 数据库提取到开发人员可能会使用的实体框架中。我也可能对 WebGrid 有点过分,它比 foreach 语句优雅得多。一个基本的@webgrid.GetHtml() 将显示每一列和每一行。
Background
背景
In this working example, users have uploaded pictures. Their pictures are displayed in their edit form using a partial view. The ImageID and FileName metadata is persisted in SQL Server while the file itself is persisted in the ~/Content/UserPictures directory.
在这个工作示例中,用户上传了图片。他们的图片使用局部视图以编辑形式显示。ImageID 和 FileName 元数据保存在 SQL Server 中,而文件本身保存在 ~/Content/UserPictures 目录中。
I know it's kinda half vast, because all the details of uploading and editing personal data isn't shown. Just the germane parts of using a Partial View are focused on, albeit with some bonus EF thrown in. The namespace is MVCApp3 for S&G.
我知道它有点大,因为没有显示上传和编辑个人数据的所有细节。只关注使用部分视图的相关部分,尽管加入了一些额外的 EF。命名空间是 S&G 的 MVCApp3。
Partial View ModelViewModels.cs
局部视图模型ViewModels.cs
The SQL Server Images table includes many more columns in addition to ImageID and FileName such as [Caption], [Description], a MD5 hash to prevent the same image being uploaded multiple times, and upload date. The ViewModel distills the Entity down to the bare minimum needed for a user to see their pictures.
除了 ImageID 和 FileName 之外,SQL Server 图像表还包含更多列,例如 [Caption]、[Description]、防止同一图像被多次上传的 MD5 哈希值以及上传日期。ViewModel 将实体提炼到用户查看图片所需的最低限度。
public class Picts
{
public int ImageID { get; set; }
public string FileName { get; set; }
}
Main View ViewEdit.cshtml
主视图视图Edit.cshtml
Note the cast/convert to strongly type the ViewData[].
请注意强制类型化 ViewData[] 的强制转换/转换。
@Html.Partial(
partialViewName: "Picts",
model: (IEnumerable<MVCApp3.Models.Picts>)ViewData["Picts"]
)
If you don't set the strongly-typed model to use for the Partial View you'll get a "The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies..." error because it assumes you're passing the parent/master model.
如果您没有设置强类型模型以用于部分视图,您将收到“传递到字典中的模型项的类型为 'System.Data.Entity.DynamicProxies...”错误,因为它假定您'正在传递父/主模型。
Partial View ViewPicts.cshtml (the whole file contents is shown)
Partial View ViewPicts.cshtml(显示整个文件内容)
@model IEnumerable<MVCApp3.Models.Picts>
@{
var pictsgrid = new WebGrid(Model);
}
@pictsgrid.GetHtml(
tableStyle: "grid",
displayHeader: false,
alternatingRowStyle: "alt",
columns: pictsgrid.Columns(
pictsgrid.Column(format:@<text><img src="@Url.Content("~/Content/Users/" + @item.FileName)" alt="@item.ImageID" width="200" />
@Html.ActionLink(linkText: "Delete", actionName: "DeletePicture", routeValues: new { id = @item.ImageID })
</text>)
))
ControllerIdentityController.cs
控制器IdentityController.cs
Set the data content into the ViewData["MyPartialViewModelKeyName"] your partial view will consume. You can give the dictionary key any name you want, but I gave it ViewData["Picts"] to be consistent with the partial view file name and its view model class definition.
将数据内容设置到您的局部视图将使用的 ViewData["MyPartialViewModelKeyName"] 中。您可以为字典键指定任何您想要的名称,但我给它指定了 ViewData["Picts"] 以与局部视图文件名及其视图模型类定义保持一致。
Because the pictures may be shared amongst multiple users there is a many-to-many table with a corresponding PITA query in Entity Framework using nested froms and inner joins to return just the pictures belonging to, or shared with, a user:
由于图片可能在多个用户之间共享,因此实体框架中有一个带有相应 PITA 查询的多对多表,使用嵌套的 froms 和内部连接来返回属于用户或与用户共享的图片:
public class IdentityController : Controller
{
private EzPL8Entities db = new EzPL8Entities();
// GET: /Identity/Edit/5
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpNotFoundResult("This doesn't exist");
// get main form data
ezpl8_UsersPhysicalIdentity ezIDobj = db.ezpl8_UsersPhysicalIdentity.Find(id)
// http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/
// get partial form data for just this user's pictures
ViewData["Picts"] = (from user in db.ezpl8_Users
from ui in user.ezpl8_Images
join image in db.ezpl8_Images
on ui.ImageID equals image.ImageID
where user.ezpl8_UserID == id
select new Picts
{
FileName = image.FileName,
ImageID = image.ImageID
}
).ToList();
return View(ezIDobj);
}
// Here's the Partial View Controller --not much to it!
public ViewResult Picts(int id)
{
return View(ViewData["Picts"]);
}
[Authorize] //you have to at least be logged on
public ActionResult DeletePicture(int id)
{
//ToDo: better security so a user can't delete another user's picture
// TempData["ezpl8_UserID"]
ezpl8_Images i = db.ezpl8_Images.Find(id);
if (i != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Users"), i.FileName);
System.IO.File.Delete(path: path);
db.ezpl8_Images.Remove(i);
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.ToString());
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
回答by user2689416
// get main form data
ezpl8_UsersPhysicalIdentity ezIDobj = db.ezpl8_UsersPhysicalIdentity.Find(id)
// http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/
// get partial form data for just this user's pictures
ViewData["Picts"] = (from user in db.ezpl8_Users
from ui in user.ezpl8_Images
join image in db.ezpl8_Images
on ui.ImageID equals image.ImageID
where user.ezpl8_UserID == id
select new Picts
{
FileName = image.FileName,
ImageID = image.ImageID
}
).ToList();
return View(ezIDobj);
}
// Here's the Partial View Controller --not much to it! public ViewResult Picts(int id) { return View(ViewData["Picts"]); }
// 这是部分视图控制器——没什么大不了的!public ViewResult Picts(int id) { return View(ViewData["Picts"]); }
[Authorize] //you have to at least be logged on
public ActionResult DeletePicture(int id)
{
//ToDo: better security so a user can't delete another user's picture
// TempData["ezpl8_UserID"]
ezpl8_Images i = db.ezpl8_Images.Find(id);
if (i != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Users"), i.FileName);
System.IO.File.Delete(path: path);
db.ezpl8_Images.Remove(i);
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.ToString());
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}

