将参数传递给我的部分视图?

发布于 2024-08-15 12:55:26 字数 155 浏览 5 评论 0原文

我这样调用我的局部视图:

 <% Html.RenderPartial("~/controls/users.ascx"); %>

我可以将参数传递给局部视图吗?我将如何在实际的 users.ascx 页面中访问它们?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自找没趣 2024-08-22 12:55:26

您可以将模型对象传递给部分(例如字符串列表):

<% Html.RenderPartial("~/controls/users.ascx", new string[] { "foo", "bar" }); %>

然后您强类型部分和 Model 属性将是适当的类型:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IEnumerable<string>>" %>

<% foreach (var item in Model) { %>
    <div><%= Html.Encode(item) %></div>
<% } %>

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 Model property will be of the appropriate type:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IEnumerable<string>>" %>

<% foreach (var item in Model) { %>
    <div><%= Html.Encode(item) %></div>
<% } %>
乜一 2024-08-22 12:55:26

RenderPartial 的另一个重载将传递您的模型。

<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>

如何访问?就像您通常对任何视图所做的那样:

<%= Model.MagicSauce %>

There is another overload for RenderPartial that will pass your model through.

<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>

How to access? Just like you normally would with any view:

<%= Model.MagicSauce %>
橘虞初梦 2024-08-22 12:55:26

花了一段时间才明白,MVC 意味着您可以以某种方式使用模型、视图和控制器来处理几乎所有事情,包括部分视图。一开始,这三个元素如何组合在一起可能有点令人生畏。直到现在我才这样做过,而且它有效——哇哦!

希望这对下一个人有帮助......抱歉,我使用的是 razor 而不是 .Net 表单。我还将数据从 SQL Server 数据库提取到开发人员可能会使用的实体框架中。我也可能对 WebGrid 有点过分了,它比 foreach 语句优雅得多。基本的 @webgrid.GetHtml() 将显示每一列和行。

背景

在本工作示例中,用户上传了图片。他们的照片使用局部视图以编辑形式显示。 ImageID 和 FileName 元数据保留在 SQL Server 中,而文件本身保留在 ~/Content/UserPictures 目录中。

我知道它有点大,因为没有显示上传和编辑个人数据的所有细节。尽管加入了一些额外的 EF,但仅关注使用部分视图的相关部分。S&G 的命名空间是 MVCApp3。

部分视图模型 ViewModels.cs

SQL Server 图像表除了 ImageID 和 FileName 之外还包含更多列,例如 [Caption]、[Description]、MD5 哈希以防止同一图像被多次上传,以及上传日期。 ViewModel 将实体提炼为用户查看图片所需的最低限度。

public class Picts
{
    public int ImageID { get; set; }
    public string FileName { get; set; }
}

主视图视图 Edit.cshtml

请注意强制类型转换/转换以强类型化 ViewData[]。

 @Html.Partial(
      partialViewName: "Picts", 
      model: (IEnumerable<MVCApp3.Models.Picts>)ViewData["Picts"]
 )

如果您没有设置用于部分视图的强类型模型,您将收到“传递到字典中的模型项的类型为“System.Data.Entity.DynamicProxies...”错误,因为它假设您正在传递父/主模型。

Partial View View Picts.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>)
            ))

Controller IdentityController.cs

将数据内容设置到您的部分视图将使用的 ViewData["MyPartialViewModelKeyName"] 中。您可以为字典键指定任何您想要的名称,但我给它 ViewData["Picts"] 是为了与部分视图文件名及其视图模型类定义保持一致。

由于图片可能在多个用户之间共享,因此实体框架中存在一个多对多表,其中包含相应的 PITA 查询,使用嵌套 from 和内部联接仅返回属于用户或与用户共享的图片:

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);
    }
}

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!

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.

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.

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.

Partial View Model 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.

public class Picts
{
    public int ImageID { get; set; }
    public string FileName { get; set; }
}

Main View View Edit.cshtml

Note the cast/convert to strongly type the 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.

Partial View View Picts.cshtml (the whole file contents is shown)

@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>)
            ))

Controller 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.

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:

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);
    }
}
高冷爸爸 2024-08-22 12:55:26
// 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);
}

// 这是部分视图控制器——没有太多内容!
公共ViewResult图片(int id)
{
return View(ViewData["图片"]);
}

[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);
}

}

// 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);
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文