Franz Justin Buenaventura Franz Justin Buenaventura - 23 days ago 13
C# Question

Returning List<Object> in HTML.BeginForm MVC 5

Hey Guys I need help on this, I know I can return

List<string>
in HTML.BeginForm which looks like this:

@using (Html.BeginForm("Test", "Home", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
<textarea name="logic" style="width: 10em; height: 10em;"></textarea>
<textarea name="logic" style="width: 10em; height: 10em;"></textarea>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}


I can return
List<string> Logic
on my Controller HTTPOST

But my question is how will I do it if I need to return a List of Object? Not using a Model because I need to return 2 Objects so I am was thinking like my controller should get it something like this

public ActionResult Test(List<Model1> model1, List<Model2> model2)


Thanks for those who can help

Answer

You can do in provided way

First declare class

 public class TestModel
    {
        public string Name { get; set; }
        public string Text { get; set; } 
    }

Second Controller to accept list of model

 [HttpPost]
        public ActionResult Test(List<TestModel> model1, List<TestModel> model2)
        {
            return View();
        }

Last, View to pass model values

@using (Html.BeginForm("Test", "Home", FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
<textarea name="model1[0].Name" style="width: 10em; height: 10em;"></textarea>
<textarea name="model1[0].Text" style="width: 10em; height: 10em;"></textarea>
<textarea name="model1[1].Name" style="width: 10em; height: 10em;"></textarea>
<textarea name="model1[1].Text" style="width: 10em; height: 10em;"></textarea>
<textarea name="model2[0].Name" style="width: 10em; height: 10em;"></textarea>
<textarea name="model2[0].Text" style="width: 10em; height: 10em;"></textarea>
<textarea name="model2[1].Name" style="width: 10em; height: 10em;"></textarea>
<textarea name="model2[1].Text" style="width: 10em; height: 10em;"></textarea>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Register" />
    </div>
</div>
}

Put the breakpoint inside Test controller you will see list populated

Comments