How to bind input field to edit for MVC model
I have the following javascript and input fields in my model.
script type="text/javascript">
function sum() {
var txtFirstNumberValue = document.getElementById('money1').value;
var txtSecondNumberValue = document.getElementById('money2').value;
var txtThirdNumberValue = document.getElementById('money3').value;
var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('Total').value = result;
}
}
</script>
<div class="form-group">
@Html.LabelFor(model => model.Total, "Total", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="Total" name="Total" />
@*@Html.EditorFor(model => model.Total)*@
@Html.ValidationMessageFor(model => model.Total)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money1, "money1", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
@*@Html.EditorFor(model => model.money1)*@
<input type="text" id="money1" onkeyup="sum();" name="money1" />
@Html.ValidationMessageFor(model => model.money1)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money2, "money2", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
@*@Html.EditorFor(model => model.money2)*@
<input type="text" id="money2" onkeyup="sum();" name="money2" />
@Html.ValidationMessageFor(model => model.money2)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.money3, "money3", new { @class = "control-label col-md-5" })
<div class="col-md-offset-0">
@*@Html.EditorFor(model => model.money3)*@
<input type="text" id="money3" onkeyup="sum();" name="money3" />
@Html.ValidationMessageFor(model => model.money3)
</div>
</div>
This all works great. When I enter a value in the 3 currency fields, the total appears in the Total field. Inside MVC, if I click on the detail view, it shows all four values, however, if I click on the edit view, all four fields are empty. The question is, how can I get the values ββand stay in edit mode?
source to share
Well, for starters, your model-related input fields are commented out:
@*@Html.EditorFor(model => model.money1)*@
To make them work, you will need to uncomment them.
You can manually fill in your markup with model values ββlike this:
<input type="text" id="money1" onkeyup="sum();" name="money1" value="@model.money1" />
This should pre-populate the input
value with the model value money1
. Though you take responsibility for manually implementing anything else that the built-in HTML helpers will provide you with. Unless there is a compelling reason not to use Html.EditorFor()
, I think this is the best option.
source to share