2017-01-15 44 views
-1

更新 这里是我的解决方案,为我工作: 我创建两个子视图之一的型号1,一个用于模型2 和在大视图模型我使其由:从View传递多个型号的ASP MVC到控制器5

@{Html.RenderPartial("view1", Model.model1);} 
@{Html.RenderPartial("view2", Model.model2);} 

,并在控制器我有行动的方法这样

BigViewModel model= new BigViewModel(); 
    return View(model); 

,我有行动的方法张贴这样的:

[HttpPost] 
    public ActionResult fun(Model1 model1,Model2 model2) 
{ 
//Logic go here 
} 

=================================

我有一个2个车型,如这样的:

public class Model1 { 
    ... more properties here ... 
} 

public class Model2 { 
    ... more properties here ... 
} 

,然后我创建了一个大模型:`

public class BigViewModel { 
    public Model1 model1 { get; set; } 
    public Model2 model2{ get; set; } 
} 

然后创建类型的强类型视图(BigViewModel) 使用户可以编辑该视图和预领域SS提交按钮返回到服务器以处理
public ActionResult test(BigViewModel model)

但该模型为空。 我需要一种方法来BigViewModel传递给controller.`

+2

如何在将视图模型传递给视图之前实例化视图模型?显示控制器代码 – Yoav

+0

您需要在调用视图时创建BigViewModel的实例。 – peval27

+0

对于这个工作,你的模型被从控制器传递到视图必须是你在你的行动 – Luke

回答

0

我有模特这样

public class Model1 
{ 
    public int Id { get; set; } 
} 

public class Model2 
{ 
    public int Id { get; set; } 

} 

public class BigViewModel 
{ 
    public Model1 model1 { get; set; } 
    public Model2 model2 { get; set; } 
} 

我httppost的操作方法是这样

[HttpPost] 
    public ActionResult Test(BigViewModel vm) 
    { 
     if (vm == null) 
     { 
      throw new Exception(); 
     } 
     return View(); 
    } 

我有这样的Razor视图

@model WebApplication2.Models.BigViewModel 

@{ 
    ViewBag.Title = "Test"; 
} 

<h2>Test</h2> 


@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>BigViewModel</h4> 
     <hr/> 
     @Html.ValidationSummary(true, "", new {@class = "text-danger"}) 
     @Html.EditorFor(s => s.model1.Id) 
     @Html.EditorFor(s => s.model2.Id) 
    </div> 


    <button type="submit">Save</button> 
} 

    <div> 
     @Html.ActionLink("Back to List", "Index") 
    </div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

它工作在我身边

相关问题