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

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)

Related

Update div using ajax.beginform inside asp mvc view

I want to show a success message after calling the following ajax.beginform
from Index view
#using (Ajax.BeginForm("Insert", "Home", new AjaxOptions() { UpdateTargetId = "result", HttpMethod = "POST" }))
{
#Html.TextAreaFor(m => m.openion)
}
this is my result div
<div id="result">
</div>
and my controller is
[Httppost]
public ActionResult InforMessage(openionModel usr)
{
return Content("Thanks for adding your openion");
}
but when i try this it is going to another view InforMessage
It is not updating the result div.
There is no Informessage Exist. Still it open a new page with message
"Thanks for adding your openion".How to solve this?
If your redirecting to another page its because you do not have the correct scripts loaded (or have duplicates or have them in the wrong order) so its doing a normal submit.
Ensure you have included (in order)
jquery-{version}.js
jquery.unobtrusive-ajax.js

Update partial view after edit

I have the following index:
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The partial Create view contains an invisible div which is used to create a new product.
After doing so the partial view ProductListControl is updated.
Now I want to do so with an edit function.
Problem: It's not possible to integrate the edit page while loading the index because at this moment I don't know which product the user wants to edit.
My thought:
I'd like to call my existing edit view in an jquery modal (not the problem) so the user can perform changes.
After saving the modal is closed (still not the problem- I could handle this) and the ProductListControl is updated (here's my problem ... :().
How am I able to do so?
I've seen some tutorials but I'd like to keep it as clean & easy as possible.
Most of them are using dom manipulating and get feedback from the server (controller) by a JsonResult.
If possible I'd like to stick to the razor syntax, no pure JavaScript or jquery and if possible I'd like to avoid JsonResults.
One way might be to use the Ajax.BeginForm for your create product view.
The Ajax.BeginForm accepts a number of AjaxOptions, one being the UpdateTargetId (your DOM id, in this case your productlist div), more info here.
Then in your product controller code you can return a partial view, with the product list. So for example:
Index.cshtml
#using (Ajax.BeginForm("AjaxSave", "Product", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "productList", InsertionMode = InsertionMode.Replace }))
{
// your form
<p>
<input type="submit" value="Save" />
</p>
}
...
<div id="productList">...
</div>
ProductController.cs
[HttpGet]
public ActionResult AjaxSave(Product product)
{
if (ModelState.IsValid)
{
// save products etc..
}
var allProducts = _productService.GetAllProducts();
return PartialView("ProductListControl", allProducts);
}
There is a nice article on about this here.

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 form and UpdateTargetId after submitting data when ModelState is Invalid

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);
}
}

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