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'
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.MyModelLater in the file, you can reference the attribute you want with
@Model.Attribute(uppercase “M”).@modeldeclares the model.Modelreferences 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, theModelobject 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
Attributeproperty 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");