将一个模型从局部视图传递到父视图,并将另一个模型绑定到同一个父视图

时间:2015-06-20 15:33:37

标签: asp.net-mvc asp.net-mvc-4 razor view model

我有一种情况,也许早些时候曾经问过,但我无法得到它。

我有partial view_SamplePartial.cshtml,父视图为Sample.cshtml。 现在我想在父视图中使用局部视图,以及将父视图与另一个模型绑定。

以下是代码:

public ActionResult Sample()
{
 Student student=new Student()
  {
    ID=101,
    Name="Sam",
    City="NY"
  };
 return View(student);
}

Sample.cshtml:

@model MultipleModels.Models.Student
@{
    ViewBag.Title = "Sample";
}
<h2>Sample</h2>
@Html.Partial("_SamplePartial",Model)

_Samplepartial.cshtml:

@model MultipleModels.Models.Student
<table>
    <tr><td>@Model.StudentID</td></tr>
    <tr><td>@Model.StudentName</td></tr>
    <tr><td>@Model.StudentCity</td></tr>
</table>

现在我希望另一个学生对象也绑定到View,但它不应该来自Partial View。 例如:

Student stdObj=new Student()
{
ID=999,
Name="Rambo",
City="Sydney"
};

上述对象也应该出现在视图中,但不应该从局部视图中作为模型传递。

专家请指导。

1 个答案:

答案 0 :(得分:0)

最终找出答案。

创建了一个ViewModel。

public class StudentViewModel()
{
public Student Obj1{get;set;}
public Student Obj2{get;set;}
}

行动方法:

public ActionResult Sample()
{
StudentViewModel vm=new StudentViewModel();
vm.Obj1=new Student{ID=101,Name="Sam",City="NY"};
vm.Obj2=new Student{ID=102,Name="Rambo",City="Sydney"};
return View(vm);
}

Sample.cshtml:

@model MultipleModels.ViewModels.StudentViewModel
@{
    ViewBag.Title = "Sample";
}
<h2>Sample</h2>
<p><b>Directly</b></p>
<table>
    <tr>
        <td>@Model.Obj1.StudentID</td>
        <td>@Model.Obj1.StudentName</td>
        <td>@Model.Obj1.StudentCity</td>
    </tr>
</table>
@Html.Partial("_SamplePartial",@Model.Obj2)
相关问题