I have a required field, string attribute{get; set} in a class and want to set it's value in razor. Is something like the following possible?
@model.attribute = "whatever'
See Question&Answers more detail:osI have a required field, string attribute{get; set} in a class and want to set it's value in razor. Is something like the following possible?
@model.attribute = "whatever'
See Question&Answers more detail:osFirst, capitalization matters.
@model
(lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view, e.g.:
@model MyNamespace.Models.MyModel
Later in the file, you can reference the attribute you want with @Model.Attribute
(uppercase "M").
@model
declares the model. Model
references the instantiation of the model.
Second, you can assign a value to your model and use it later in the page, but it won't be persistent when the page submits to your controller action unless it's a value in a form field. In order to get the value back in your model during the model binding process, you need to assign the value to a form field, e.g.:
Option 1
In your controller action you need to create a model for the first view of your page, otherwise when you try to set Model.Attribute
, the Model
object will be null.
Controller:
// This accepts [HttpGet] by default, so it will be used to render the first call to the page
public ActionResult SomeAction()
{
MyModel model = new MyModel();
// optional: if you want to set the property here instead of in your view, you can
// model.Attribute = "whatever";
return View(model);
}
[HttpPost] // This action accepts data posted to the server
public ActionResult SomeAction(MyModel model)
{
// model.Attribute will now be "whatever"
return View(model);
}
View:
@{Model.Attribute = "whatever";} @* Only do this here if you did NOT do it in the controller *@
@Html.HiddenFor(m => m.Attribute); @* This will make it so that Attribute = "whatever" when the page submits to the controller *@
Option 2
Or, since models are name-based, you can skip creating the model in your controller and just name a form field the same name as your model property. In this case, setting a hidden field named "Attribute" to "whatever" will ensure that when the page submits, the value "whatever" will get bound to your model's Attribute
property during the model-binding process. Note that it doesn't have to be a hidden field, just any HTML input field with name="Attribute"
.
Controller:
public ActionResult SomeAction()
{
return View();
}
[HttpPost] // This action accepts data posted to the server
public ActionResult SomeAction(MyModel model)
{
// model.Attribute will now be "whatever"
return View(model);
}
View:
@Html.Hidden("Attribute", "whatever");