How can I read a custom field in ASP.NET MVC?

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.

Upvotes: 0

Views: 410

Answers (1)

kspearrin
kspearrin

Reputation: 10748

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"]

Upvotes: 2

Related Questions