I would like to try to assign a variable value to input hidden field in my MVC form. I thought I could do it this way but the values of variables are not being put to the hidden fields.
Any thoughts why this is a wrong way?
note: there is some code in between the variables declaration … I just wanted to make things simple to read. The particular line of code that bugs me is: @value = @secondNumber
@{
ViewBag.Title = "Jakub Holovsky - Contact";
Random randomNumber = new Random();
int firstNumber = randomNumber.Next(0, 11);
int secondNumber = randomNumber.Next(0, 11);
int sumNumber = firstNumber + secondNumber;
}
<div class="divLeftSide">
<span>How much is @firstNumber + @secondNumber:</span>
@Html.TextBoxFor(m => m.FirstNumber, new { @type = "number", @id = "firstNumber", @class = "HiddenField", @value = @firstNumber })
@Html.TextBoxFor(m => m.SecondNumber, new { @type = "number", @id = "secondNumber", @class = "HiddenField", @value = @secondNumber })
</div>
1) Create a class named SomeModel for your model. The class should contain the properties named FirstNumber and SecondNumber.
2) Add the line
to your view.
3) Move
into your controller’s action.
4) In your controller’s action, initialize a new instance of SomeModel named model and set the FirstNumber to firstNumber and SecondNumber to secondNumber
5) Pass the model to your view by calling return View(model);
6) Remove the @value = @firstNumber and @value = @secondNumber from your view.