34

私は自分の部分的なビューを次のように呼んでいます:

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

パラメータを部分ビューに渡すことはできますか?実際のusers.ascxページでそれらにアクセスするにはどうすればよいですか?

4

4 に答える 4

32

モデルオブジェクトをパーシャル(たとえば、文字列のリスト)に渡すことができます。

<% 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>
<% } %>
于 2009-12-15T17:49:39.073 に答える
17

モデルを通過させるRenderPartialの別のオーバーロードがあります。

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

アクセスする方法は?通常のビューと同じように:

<%= Model.MagicSauce %>
于 2009-12-15T17:48:17.950 に答える
6

沈むのにしばらく時間がかかりましたが、MVCとは、部分ビューを含むほぼすべての目的で、モデル、ビュー、およびコントローラーを何らかの方法で使用することを意味します。3つの要素すべてがどのように組み合わされるかは、最初は少し怖いかもしれません。私は今まで一度もやったことがありませんでした、そしてそれはうまくいきます--Woohoo!

これが次の人に役立つことを願っています....申し訳ありませんが、.Netフォームの代わりにかみそりを使用しています。また、SQLServerデータベースからEntityFrameworkにデータをプルしています。これは、開発者が使用する可能性があります。また、おそらくWebGridを少しやりすぎました。これは、foreachステートメントよりもはるかにエレガントです。基本的な@webgrid.GetHtml()は、すべての列と行を表示します。

バックグラウンド

この作業例では、ユーザーが写真をアップロードしています。それらの写真は、部分ビューを使用して編集フォームに表示されます。ImageIDとFileNameのメタデータはSQLServerに保持されますが、ファイル自体は〜/ 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...」エラーが発生します。 '親/マスターモデルを渡します。

部分ビュービュー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>)
            ))

コントローラーIdentityController.cs

部分ビューが使用するViewData["MyPartialViewModelKeyName"]にデータコンテンツを設定します。辞書キーには任意の名前を付けることができますが、部分的なビューファイル名とそのビューモデルクラス定義と一致するように、ViewData["Picts"]を付けました。

写真は複数のユーザー間で共有される可能性があるため、Entity Frameworkには対応する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);
    }
}
于 2012-06-12T19:04:29.920 に答える
0
// 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);
}

//これがPartialViewControllerです-それほど多くはありません!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);
}

}

于 2013-08-16T12:36:59.727 に答える