Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...