Ajax form and UpdateTargetId after submitting data when ModelState is Invalid - ajax

On my view, I have 2 partial views.
1st partial view (PV1): user can type an item in a textbox and submit through an ajax form.
2nd partial view (PV2): user can see a list of items previously submitted.
The PV1 uses UpdateTargetId on a div on the PV2 because we would like to update our list with the newly added item.
Everything works well when items submitted on the PV1 are valid. It doesn't work when ModelState.IsValid == false when ajax form is submitted. It doesn't work because the UpdateTargetId is located on the PV2, and I need to update the PV1 for showing the ModelState Errors. So we encounter with duplicate of the PV1 on the PV2!
Below is another stackoverflow post on a similar problem but no solutions has been provided.
ASP.NET MVC AJAX change UpdateTargetId if ModelState is invalid
I think a Json alternative may be a solution but I'm wondering if we can adapt the standard Ajax form method to suit our need here?

Instead of using UpdateTargetId, you could try using OnComplete:
#using (Ajax.BeginForm(new AjaxOptions { OnComplete = "complete" }))
{
...
}
and inside this handler test whether there is an error in the resulting view:
function complete(result) {
var isError = $('span.field-validation-error', result.responseText).length > 0;
if (isError) {
// there was an error => we update the container of the form
$('#frmContainer').html(result.responseText);
} else {
// no error => we hide validation errors and update the result container
$('#frm .field-validation-error').hide();
$('#frm .input-validation-error').removeClass('input-validation-error');
$('#result').html(result.responseText);
}
}

Related

Why can I not reuse a method in an Ajax form in a partial view?

I'm working on an MVC Application that has a basic ajax form for submitting data. After the form, there is a partial view which has another ajax form in it for submitting data to a drop-down box allowing users to update its contents without leaving the page.
Create
#model My Project.Models.Cars
#using (Ajax.BeginForm("Create", "Cars", new AjaxOptions
{
HttpMethod = "POST"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
... form fields would be here ...
}
#Html.Partial("_Manufacturer")
Partial View(_Manufacturer)
#using (Ajax.BeginForm("AddManufacturer", "AnotherController", new AjaxOptions
{
HttpMethod = "POST"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
... form fields for populating dropdown list ...
}
When I try to submit the ajax form in the partial view I am getting an error of:
404 Resource Not Found at Cars/AddManufacturer
The controller it's supposed to use is AnotherController as you can see in the form above. I don't want to have to create multiple forms and methods, I want to reuse the method I have. Is there a reason it's doing this and is there anything I can do about it?
Sometimes partials render URLs differently accordingly to where they are called from.
Inspect your page and see if the URL rendered on the second form is right. If that is the case then find a method overload that can resolve the route correctly.
Here is a list of the overloads:
https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd492974(v=vs.118)

Validate only ajax loaded partial view

I have a form with some controls. There is a button on the form which loads a partial view. Inside the partial view, there are two required field textboxes along with a button. And when its clicked, I need to display error messages only for textboxes which are inside the partial view, but not for the fields in the actual form. And when I click form's submit button, all error messages must show up.
After partial view is loaded, I am re-initializing the validation plugin as below.
$('#test').removeData("validator");
$.validator.unobtrusive.parse('#test');
I tried using validation attribute described in below thread but its not working. Maybe it works for normally loaded views.
ASP.NET MVC Validation Groups?
However, I can validate individually by calling textbox1.valid() and textbox2.valid(). But I think I am missing standard way of doing it. Any help is appreciated.
you can do this by submitting your partial view using Ajax.BeginForm()
//In Partail View
#model SomeModel
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId"}))
{
#Html.EditorFor(mode=>model.FirstText)
#Html.EditorFor(mode=>model.SecText)
<input type="submit" value="save">
}
//In Controller
public ActionResult SomeAction(SomeModel model)
{
return PartaiulView(model);
}
here you can validate your Partial View
NOTE: when you submit you form using Ajax.BeginForm you must specify "UpdateTargetId" where your result will be appear on View.
//In View
<div id="targetId">
#Html.Partail("PartialView")
</div>
OR if you want to Redirect to another action if your model is valid then modified your action
public ActionResult SomeAction(SomeModel model)
{
if(ModelState.IsValid)
{
return Json(new {redirect = #Url.Action("SomeAction","SomeController")})
}
return PartaiulView(model);
}
then in partail view you can invoke OnSuccess method of Ajax.BeginForm
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId",OnSuccess="success"}))
{
}
<script type="text/javascript">
function success(data)
{
if(data.redirect)
{
windows.location = data;
}
}
</script>
check both way which one is suitable to you.

Ajax.BeginForm with OnComplete always updates page

I have simple ajax form in MVC. In AjaxOptions there is OnComplete set to simple javascript function which does one thing - returns false.
#using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { UpdateTargetId = "DivFormId", HttpMethod = "Post", OnComplete = "preventUpdate" }))
function preventUpdate(xhr) {
return false;
}
The problem is, that page is already updated. E.g. in one case controller returns partial view after postback, in other case it returns some Json object. I want it to update page when partial view is returned, and to show dialog window when json is returned. Unfortunately when json is returned, it clears the page (update it with json) even when OnComplete function returns false as MSDN says: To cancel the page update, return false from the JavaScript function.
How to prevent page update depending on received response?
Thank you!
----- UPDATE -------
So far I found following solution. When I don't specify UpdateTargetId, I can do manually with the response what I want. But it is still not documented behaviour with return false.
Use OnSuccess and get rid of UpdateTargetId. Like this:
#using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "Post", OnSuccess = "foo" }))
{
...
}
and then:
function foo(result) {
if (result.SomePropertyThatExistsInYourJsonObject) {
// the server returned a JSON object => show the dialog window here
} else {
// the server returned a partial view => update the DOM:
$('#DivFormId').html(result);
}
}

How to Execute ASP.Net MVC Ajax.ActionLink Only After Validation?

Net MVC 3.0 Project
I have a form in my page and a Ajax.ActionLink which adds another set of Fields to the current form, and this is a repetitive process, as long as user keeps clicking the ActionLink, it will keep adding more and more set of Fields to the form.
Here is my Ajax Action Link
#Ajax.ActionLink("Add Another ERx", "ERxView", "Medication", new AjaxOptions
{
UpdateTargetId = "accordion",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod = "POST",
OnBegin = "destroyAccordion",
OnSuccess = "createAccordion"
}, new { #class = "standard button", id = "AnotherErx", onclick = "document.ERxForm.submit();"})
My Problem is
When user clicks on the link it should first validate the current form for all required fields, upon successful validation only it should append the new set of Fields to the form.
I tried something like this in my Ajax.ActionLink to validate current form upon clicking the ActionLink
onclick = "document.ERxForm.submit();"
this fires an Form Validation, But irrespective of Validation, it continues adding the new set of fields to the form.
Can any one help me, How can I achieve this
Thank for all who is taking time to read my question.
The issue most likely is that you are adding new elements to be validated. If you add new validation elements via AJAX, it is necessary to clear and re-parse all validation attributes on the page, like so:
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
Add this to your OnSuccess function, and the validation will work for all elements on the page, original and added.
OnBegin = "destroyAccordion"
Make destroyAccordion function call validation function and return true or fals.
If it is true then Action link executes.

ASP.NET MVC 2 - how to get Ajax.BeginForm work properly inside partial view

I have a View with url like
/Home/SetResults?patientId=[somePatientId]
, part of it gets conditionaly ajax-updated with some partialview
Inside of that partialView I have this code
<% using (Ajax.BeginForm("Action", "Home", new AjaxOptions { UpdateTargetId = "placeholder", InsertionMode = InsertionMode.Replace,HttpMethod = "Post"}))
{%>
<div id="placeholder">
....
Whenever I press submit button I get to my simple controller action-method
[HttpPost]
public ActionResult Action(MyModel model)
{
return PartialView();
}
Everything works fine except the ajax itself - instead of gettin my placeholder updated with the result of controller action I'm always getting redirect to a view with the url of
/Home/Action
So, is it possible to partially update partial view? If yes what I'm doin wrong?
One thing to check would be that you are including the ajax script:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
I've noticed if this isn't included, submitting the Ajax form behaves like a regular submit.

Resources