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'
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'
First, 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
, theModel
object will be null.Controller:
View:
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 withname="Attribute"
.Controller:
View:
@Html.Hidden("Attribute", "whatever");