I'm trying to assign value to the hidden field in java script using the JavaScript variable and trying to pass it back to the controller. The value every time I go in the post method for my model property DBErrorID is 0.
Razor View:
<body>
@Html.HiddenFor(model => model.DBErrorID, new { id = "DBErrorId" })
<input type="submit" value="Update" class="btn btn-success" onclick="GetValue()" />
</body>
JavaScript:
<script language="javascript" type="text/javascript">
function GetValue() {
$("#DBErrorId").val(totalValues);
// alert(totalValues);
}
<script>
Controller:
[HttpPost]
public ActionResult ErrorStatusView(Models.ErrorStatusModel obj)
{
Models.ErrorStatusModel objreg = new Models.ErrorStatusModel();
objreg.DBErrorID = obj.DBErrorID;
}
Your current server side code is creating an unnecessary new object of
ErrorStatusModelas the first line, which will create a new object(objregvariable) with default values(unless you are setting it in a constructor), for aninttype property it will be0. If you are inspecting the values ofobjreg, that is the reason you see0as the property value.You do not need to create this additional object. The model binder framework will create one for you and map the posted values, when you use
ErrorStatusModelyour method parameter type. That means yourobjproperty is properly populated by the form data (assuming theDBErrorIDproperty is settable)Also, your client side code is trying to set the value of hidden input inside the
GetValuemethod which is called on theonclickevent of the submit button. If you are using a normal form submit and your button is inside a form tag, when user clicks on the submit button it will immediately submit the form (with the current value of that input)If that is the case, you should prevent the default behavior (submitting the form) when the button is clicked, set the value as needded and fire the form submit via JavaScript.
There are multiple ways to do it. Here is one approach- the unobtrusive JavaScript approach- which assumes you have jQuery loaded to your page. Give an
Idto the button, which we can use to wireup the click event.Now in JavaScript, listen to the click event on this button, prevent the normal behavior(submitting the form), update the hidden input value and trigger the form submit.
Also you should not create a new object in server