My scenario here is that on my View
, I have multiple field to input number and one field to auto generated result by a formula. I want to be able to pass those value back to my Controller
, from there I will calculate and return the result back to View
while the input value to calculate still remain. The reason why I don't perform this on my Javascript
is because there are some condition that require me to interact with value from lots of others field in others data in database
. I intend to do this by passing a whole set of Model
from View
to Controller
, and I don't want to reload the page whenever an input field is input. So far, here's my two methods:
Using Javascript Ajax
:
var modelObject = @Html.Raw(Json.Serialize(Model));
This allow me to store and passing Base Model
at the beginning only. I can't pass new input value. Is there away for the input to automatically store their value in Model
to be used in the code similar to the above?
Using Unobtrusive AJAX
and Javascript
to activate submit action:
function submit(){
$('#formSubmit').submit();
--OR--
$('#btnSubmit').click();
}
<form id="formSubmit" data-ajax="true" asp-action="Action" method="POST">
<input asp-for="Item.inputValue" onchange="submit()"/>
<button id="btnSubmit" type="submit"></button>
</form>
The button when click works fine with Unobtrusive AJAX
. But the Javascript
to activate the submit event can't. My page still reload.
What is the right way for me to go? And in which of them, how do I need to fix my code to make it run like I want?
When using JQuery Ajax to pass the data, you should use the serialize() method to serialize the form, then pass the form data to the controller action method. Code as below:
When using the jQuery Unobtrusive AJAX, first, please make sure you have added the jQuery Unobtrusive AJAX reference in current page, then, make sure you have activated unobtrusive Ajax on the target element.
For example, using the following code, after clicking the submit button, it will submit the
mainform
to the ProductIndex action method, then update thediv_partial
contents:More detail information about using jQuery Unobtrusive AJAX, refer this link.
The detail sample code as below:
Model:
Controller:
PartialView (_PVProduct.cshtml): Here I use a partial view to display the Model content, it is easier to update the content with Ajax.
View Page ():
At the end the above view page, add the following scripts: Here I use the jQuery Unobtrusive AJAX CDN reference:
The output as below: