I am a bit stuck trying to figure out on how to show the value of a field model.SumValue
which I am calculating in the controller class in a input field or a label.
Controller class –
public IActionResult Index()
{
var model = new SumModel();
return View(model);
}
[HttpPost]
public IActionResult Sum(SumModel model)
{
model.Sum= Sum();
return View();
}
Model class –
public class SumModel
{
public string SumValue { get; set; }
}
View class-
@model YourNamespace.SumModel
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<label>Sum Value:</label>
<input type="text" value="@Model.SumValue" readonly />
</body>
</html>
I am trying to set the field name this way into the <input/>
field.
<input type="text" asp-for="SumValue" />
Can anyone point out where I am going wrong here?
Update – When I attempt to display the value it is taking me to a different page /Home/Sum
and it says it cannot find the value.
2
Answers
When passing to the view date model of type
SumModel
the same type should be declared in the view:The
@Model
prefix might be omitted, because of the compiler construct attributesid
andname
using the model declaration used in the@model
definition.After you have updated your question we can see that the
SumValue
isn’t initialized. Try to define some value:Also, to check what is the HTML content is generated be Razor engine use mouse right click in the browser and select
View Page Source
in the popup menu. This will help you to understand what HTML code is generated from your.cshtml
and will give you more useful information.Assuming you have to show the updated value on Index Page, in that case your code should look like:
This will show value in your Read only field on your Index Page
In this case issue was that you were not passing updated SumValue value in model.
I hope this solves your issue