0

Is there a way to obtain a model object from the view into the controller without using strongly typed HTML helpers. The View uses the Account entity But need to post the form and retrieve the account entity of the variable running in a foreach loop used to generate the table/grid of values. The information from the dropdown is used for a different entity hence why its not strongly typed.

public class HomeController : Controller
{
    // GET: Home
    ModelContext model = new ModelContext();


    [HttpGet]
    public ActionResult Index()
    {


        return View(model.accounts.ToList());
    }

    [HttpPost]
    public ActionResult Index(Account account,List<string> status,string name)
    {
      // return student object
        return View();
    }
}

The rest of the code in the View runs on a foreach loop to generate an html table enclosed in a @HTML.BeginForm

<td>

        @Html.DropDownList("status",
        new SelectList(Enum.GetValues(typeof(ProjectName.Models.Code))),
        "...",
        new { @class = "form-control" })

</td>

<td>
    @Html.TextArea("comment");
</td>
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Mark Evans
  • 37
  • 8
  • Your `DropDownList()` method posts back only a single value so the parameter needs to be `string status` (not `List status`). But having said that, you should be using view model containing all the properties you want in the view so you can strongly bind to it, get validation etc. –  Nov 24 '16 at 01:53
  • It returns an array of input because its running inside a foreach loop – Mark Evans Nov 24 '16 at 01:55
  • Then you generating invalid html for a start! And you definitely need a view model to handle this properly –  Nov 24 '16 at 01:57
  • But how will the view model work with the Context Class? @StephenMuecke – Mark Evans Nov 24 '16 at 02:08
  • What `Context` class? - are you referring to you db context? - is so, then there is no relationship to it - you map your data models to view models as vice-versa –  Nov 24 '16 at 02:11
  • I am retrieving data from the database using the dbcontext class initialised in the controller noted above. in the view HTML helpers will only accept a single type. if I create a 3rd class encapsulating both types i will no longer be able to access the db context mappings because its done on individual classes that map to database table names – Mark Evans Nov 24 '16 at 02:18
  • [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Nov 24 '16 at 02:19

1 Answers1

1

You should be created a parent view model that includes both of these view models that you'll be needed in your view. For example:

public class ViewModel
{
    public ProjectName.Models.Code Code {get; set;} 
    public ProjectName.Models.Account Account {get; set;}
}

Also, please have a look MVC - Multiple models in a view. I think it's good for you.

Hope this help!

Community
  • 1
  • 1
Ha Hoang
  • 1,644
  • 12
  • 14