Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC pass model to view

My Index.cshtml

@model ReportGenerator.WebUI.Models.ReportViewModel
@Html.TextBoxFor(m => m.report.FileName, new { @class = "form-control", id = "FileName" })

My controller

public ActionResult Index(ReportViewModel model)
{
    ...some stuff
    model.report = new Report();
    model.report.FileName = "INDEX";
    return View(model);
}

public ActionResult fillFields(ReportViewModel _model)
{
    ...some stuff
    _model.report = new Report();
    _model.report.FileName = "FILL";
    return View("Index", _model);
}

When I run my application the TextBox Text property is set to "INDEX". Also when I click on a button which calls the fillFields controller action, the TextBox is still displaying "INDEX", it's not changing to "FILL".

What am I doing wrong? Why it doesn't want to work?

like image 355
Icet Avatar asked Oct 05 '15 09:10

Icet


People also ask

How do you pass a model to view?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

How pass data from view to view in MVC?

ViewBag. ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary.

How do I pass model list from Controller view?

You can use for this: 1 - Using View() , 2 - Using ViewData , 3 - Using ViewBag , 4 - Using your custom class , and 5 - Some combinations of those approaches.


1 Answers

@StephenMuecke answered this correctly in the comments above.

Your not doing anything wrong. Your fillFields() method has a parameter ReportViewModel so its values are added to ModelState when the method is initialized. When you return the view, your TextBoxFor() method uses the value from ModelState (not the model property) to set the value of the textbox. The reason for this is explained here. The correct approach is to follow the PRG pattern –

like image 148
Mihir Kale Avatar answered Sep 28 '22 05:09

Mihir Kale