Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c# - Passing multiple models from View to Controller in asp MVC 5

Update here is my solution that worked for me: I create two sub views one for Model1 and one for Model2 and in the big view model I render them by :

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

and in the controller I have Action method like this

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

and I have Action method for posting like this :

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

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

I have a 2 models like this :

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

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

and then I created one big model : `

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

then created a strong typed view of type (BigViewModel) so that user can edit the fields in that view and press submit button to back to server to process
public ActionResult test(BigViewModel model)

but the model is null. I need a way to pass the BigViewModel to the controller.`

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have models like this

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; }
}

I have httppost action method like this

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

I have razor view like this

@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")
}

It works on my side


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...