-->

MVC 4 - 我该怎么办模型数据传递给局部视图?(MVC 4 - how do I pass m

2019-07-20 18:04发布

我建设,将有一个数字,涉及特定型号(租客)部分的个人资料页 - AboutMe,MyPreferences - 这种事情。 这些部分的每一个将是一个局部视图,允许使用AJAX的部分页面更新。

当我点击了ActionResult在TenantController我能创造一个强类型的视图和模型的数据传递给视图的罚款。 我不能局部视图实现这一目标。

我创建了一个局部视图_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 ? 如果我失去了一些东西有关的概念,请解释。

Answer 1:

你不是真正传递模型的部分,你传递一个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>


Answer 2:

此外,这样可以使它的工作原理:

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

要么

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

对于MVC上的RenderPartial和类似HTML的帮手更多信息,请参见本流行的StackOverflow线程



Answer 3:

三种方式来传递模型数据到局部视图(可能有更多)

这是视图页面

方法一填充在视图

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



文章来源: MVC 4 - how do I pass model data to a partial view?