簡體   English   中英

MVC 4 - 如何將模型數據傳遞給局部視圖?

[英]MVC 4 - how do I pass model data to a partial view?

我正在構建一個個人資料頁面,該頁面將包含許多與特定模型(租戶)相關的部分 - AboutMe、MyPreferences - 諸如此類。 這些部分中的每一個都將是一個局部視圖,以允許使用 AJAX 進行局部頁面更新。

當我單擊 TenantController 中的ActionResult時,我能夠創建一個強類型視圖,並將模型數據傳遞給視圖。 我無法通過部分視圖實現這一點。

我創建了一個局部視圖_TenantDetailsPartial

@model LetLord.Models.Tenant
<div class="row-fluid">
    @Html.LabelFor(x => x.UserName) // this displays UserName when not in IF
    @Html.DisplayFor(x => x.UserName) // this displays nothing
</div>

然后我有一個視圖MyProfile將呈現提到的部分視圖:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", 
         new ViewDataDictionary<LetLord.Models.Tenant>())
    </div>
</div>

如果我將代碼包裝在 DIV 中的_TenantDetailsPartial @if(model != null){}頁面上不會顯示任何內容,所以我猜有一個空模型被傳遞給視圖。

當我從ActionResult創建強類型視圖時,“會話”中的用戶如何傳遞給視圖? 如何將“會話”中的用戶傳遞到不是從ActionResult創建的部分視圖? 如果我遺漏了一些關於這個概念的東西,請解釋一下。

您實際上並沒有將模型傳遞給 Partial,而是傳遞了一個new ViewDataDictionary<LetLord.Models.Tenant>() 試試這個:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

此外,這可以使它起作用:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

要么

@{
Html.RenderPartial("your view", your_model);
}

有關 MVC 中 RenderPartial 和類似 HTML 助手的更多信息,請參閱此流行的 StackOverflow 線程

將模型數據傳遞給局部視圖的三種方式(可能還有更多)

這是查看頁面

方法一在視圖中填充

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

方法二通過ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

方法三通過模型

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

在此處輸入圖片說明

我知道問題特定於 MVC4。 但是由於我們已經超越了 MVC4 並且如果有人在尋找ASP.NET Core ,您可以使用:

<partial name="_My_Partial" model="Model.MyInfo" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM