0

I have a model with a controller and views. In the "create" view I added a field that does not belong to the model.

How can I read the field in the controller?

Thank you very much.

Allfarid Morales García
  • 1,455
  • 2
  • 17
  • 27
  • You can use `Request.Form["yourFieldName"];` but what you really should be doing is using a view model with the additional property –  Jun 09 '15 at 01:38
  • Every result in google told me to use the view models, but you solved my problem in ten seconds. If you post it as an answer I'll mark it as the solution. Thank you very much. – Allfarid Morales García Jun 09 '15 at 01:43
  • The reason _"Every result in google told me to use the view models"_ is because that's what you **should** be doing! –  Jun 09 '15 at 01:45
  • I'm sorry. I already spent several sessions trying to understand viewmodels but I am still too noob – Allfarid Morales García Jun 09 '15 at 01:48
  • [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc). Begin you MVC adventure using best practices :) –  Jun 09 '15 at 01:52

1 Answers1

2

You can access properties that are not in your View Model by accessing Request.Form["Property"]. Please see the following example:

https://dotnetfiddle.net/riyOjb

It is recommended that you do you view models, however.

View Model

public class SampleViewModel
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new SampleViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SampleViewModel model)
    {
        // model.Property1 is accessable here
        // as well as model.Property2

        // but if you want something not in the view model, use Request.Form
        ViewData["CustomProperty"] = Request.Form["CustomProperty"];
        return View(model);
    }
}

View

@model MvcApp.SampleViewModel
@using(Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Property1)<br /><br />
    @Html.TextBoxFor(m => m.Property2)<br /><br />
    <input type="text" name="CustomProperty" id="CustomProperty" /><br /><br />
    <button type="submit" class="btn">Submit</button>
}

<h2>Submitted Data</h2>
@Model.Property1<br />
@Model.Property2<br />
@ViewData["CustomProperty"]
kspearrin
  • 10,238
  • 9
  • 53
  • 82
  • When I try to create a viewmodel I am asked to add an ID to the model, and the system creates a completely new model with its own table. I've already tried for several days to learn how to create a viewmodel, but everything is useless. – Allfarid Morales García Jun 10 '15 at 05:04