In fact beyond the jQuery you need the plugin Microsof jQuery Unobtrusive Ajax which can be obtained via Nuget.
So the minimum structure to carry out the process is:
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
And the helper is at least so:
@using (Ajax.BeginForm("Novo", "Cliente", new AjaxOptions
{
OnSuccess = "OnSuccess"
}))
{
<button type="submit">Submit</button>
}
And the Javascript function Onsuccess:
<script type="text/javascript">
function OnSuccess(response) {
if (response && response.data) // verifica se response e se response.data existe
alert(response.data);
}
</script>
This way you can use the Ajax.BeginForm
. If you want to avoid another plugin just for sending requests Ajax, you can do manually without the need of Unobtrusive Ajax:
@using(Html.BeginForm("Novo", "Cliente", FormMethod.Post, new { id = "formCliente" }))
{
<button type="submit">Submit</button>
}
With a script:
$(function () {
$("#formCliente input[type=submit]").click(function (event) {
event.preventDefault();
var form = document.getElementById("formCliente");
var data = $(form).serialize();
$.post(form.action, data, function (response) {
if (response && response.data)
alert(response.data);
});
});
});
And if you use the Unobtrusive Validate:
$(function () {
$("#formCliente input[type=submit]").click(function (event) {
event.preventDefault();
var $form = $("#formCliente");
$form.validate();
if ($form.valid) {
var data = $form.serialize();
$.post($form.attr("action"), data, function (response) {
if (response && response.data)
alert(response.data);
});
}
});
});
Returns the white page,with the value 1 only, yes, if it is not valid returns the view, otherwise it should return this Id so I can treat it in the client
– Rod
It is in the whole page and has yes button of Submit
– Rod
Hi Tiago, I searched here and saw that to use the Ajax helper, you need the lib jquery unobtrusive ajax
– Rod
I hadn’t even touched myself, so if you want to make an answer and referenced that, you can do...
– Rod
Tiago, actually, my validation is all in the client, the Modelstate would be used to return the view with validation if the js is disabled, another thing I omitted, is that I have 2 Ubmit, one that saves and is directed to my Index, and another that enables other information from the registration screen, so for this I return a Json with the Id that has just been saved
– Rod