MVC Multiple Ajax Calls - ajax

I am having trouble making ajax calls in my MVC application. I have tried two different ways to be able to have an ajax actionlink load a partial and then that partial submit a form as an ajax call, but I am having trouble.
First Attempt
// will load the partial page and will submit the form successfully, but each time an actionlink is clicked it will load another ajax script so when clicking on an actionlink it will call to the controller one time on first click, two times on second, etc...
Index.cshtml
#Ajax.ActionLink("Car 1, "EditCars", new { role = #Model.Car1}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "permissions",
})
#Ajax.ActionLink(Car 2, "EditCars", new { role = #Model.Car2}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "permissions",
})
<div id="permissions"></div>
// need to include this script to get the ajax action links to work
#Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")
EditCars.cshtml
#using (Ajax.BeginForm("EditCars", "CarManagement", new AjaxOptions()))
{
#Html.EditorFor(model => model.CarName)
<input type="submit" />
}
// need to include this script to get the ajax submit form to work
#Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")
Second Attempt
// the action links work, but the ajax submit form does not. The controller returns to a new page
Index.cshtml
#Ajax.ActionLink("Car 1, "EditCars", new { role = #Model.Car1}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "permissions",
})
#Ajax.ActionLink(Car 2, "EditCars", new { role = #Model.Car2}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "permissions",
})
#using (Ajax.BeginForm("EditCars", "CarManagement", new AjaxOptions()))
{
<div id="permissions"></div>
<input type="submit" />
}
// need to include this script to get ajax calls to work
#Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")
EditCars.cshtml
#Html.EditorFor(model => model.CarName)

Get the latest version of jQuery.unobtrusive-ajax.js using Nuget Manager:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Related

How to get full AJAX URL request after Ajax.BeginForm complete?

In my code, when user presses the submit button, it will execute an AJAX request to the controller.
It's all doing fine, however, I also wanted to update the browser URL to include the full query string (e.g. http://localhost/Forecast?BillingToes=123&Year=2016).
The Controller is returning a partial view with a model. Adding an additional property containing the full URL with query string seems to be OK. However, it seems pretty awkward.
So my question is, is there a way to retrieve the full URL via JavaScript after OnComplete? Below is my View:
#using (Ajax.BeginForm("UpdateForecast", null, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "forecastControlPart",
LoadingElementId = "ajaxSpinnerImage",
OnBegin = "DeactivateForm",
OnSuccess = "initAppendHeader();UpdateURL(xhr)",
OnComplete = "ReloadFiltersBehaviour"
}, new
{
#class = "onChangeForm",
data_currencyurl = #Url.Action("GetCurrencyForBilling", "DataSource"),
}))
I found the solution to my problem, using $(form).serialize() can fetch all the parameters the form submit to the server, so my code would look like:
In my View:
#using (Ajax.BeginForm("UpdateForecast", null, new AjaxOptions {
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
OnSuccess = "initAppendHeader(),UpdateURL(this)",
}))
In my Javascript file:
function UpdateURL(form) {
// Auto-Update browser URL to include parameters after submit.
var formData = $(form).serialize();
window.history.pushState(null, null, formData);
}

Ajax Helper not redrawing the form

I'm trying to use Ajax.BeginRouteForm to create a list of results that can be paged and searched. The general idea is that the menu at the top of view and the layout would not be redrawn, but the central area with the search results would be.
So I have two controller actions, a GET, which returns an initial model and the view, and a POST, which takes the model, gets the page/search info from it, and runs the search, returning the same model and view.
What I'm seeing is that the POST works, the new results are obtained, and the view is being compiled with those new results (debug code tells me this), but clientside the form is not being redrawn.
When I add the InsertionMode and UpdateTargetId params, I get the view-inside-the-view issue, where the whole menu is being rendered inside the form area.
#using (Ajax.BeginRouteForm(ContentRoutes.EmailContentList,
new { instance = UserContext.InstanceId },
new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "blockForm();",
OnComplete = "unblockForm();",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "frmContent"
},
new { id = "frmContent" }))
{
You should have an outside div with ID frmContent containing the form
<div id="frmContent">
#using (Ajax.BeginRouteForm(ContentRoutes.EmailContentList,
new { instance = UserContext.InstanceId },
new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "blockForm();",
OnComplete = "unblockForm();",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "frmContent"
}
}
</div>
This is because you are adding the result of the AJAX call to the frmContent HTML element.
Also, you should make sure that AJAX actually works: Use if (Request.IsAjaxRequest()) inside your Action and inspect it's value with the debugger.

mvc3 ajax prepoluate textbox

I have a controller that uses ajax.actionlink in order to get a partial view from another controller. My question is how can I use the result from that ajax partialview to fill in a textbox in my main action .
This is the view i'm working on corresponds to this view
#Ajax.ActionLink("Find location", "getzipcode",
new AjaxOptions
{
UpdateTargetId = "ajax_insert",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
});
<div id="ajax_insert">
</div>
#using (Html.BeginForm("create", "service", FormMethod.Post))
{
// fill Ajax code in this EditFor Result
#Html.EditorFor(model => model.zipcode)
}
as you can see above that ajax simply request's a partial view called getzipcode which just links to this action
public PartialViewResult getzipcode()
{
var zipco = (from s in db.servicers where s.zipcode == 32839 select s);
return PartialView("_review", zipco);
}
The ajax works correctly, im just stumped on inserting the zipcode into the EditFor box as well I tried
#Html.EditorFor(model => model.zipcode,#ajax_insert) but it did not work.
You can make use of onSuccess callback function
#Ajax.ActionLink("Find location", "getzipcode",
new AjaxOptions
{
UpdateTargetId = "ajax_insert",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnSuccess = "fillTextBox"
});
<script type="text/javascript>
function fillTextBox(){
//Use jquery to fill your text box
}
</script>

Set UpdateTargetId dynamically or change UpdateTargetId

I have a view where i am using the:-
#using (Ajax.BeginForm("Edit", "Files", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divFile-" + Model.FileId,
OnSuccess = "editPrivilegeLevelForFileSuccess",
OnFailure = "editPrivilegeLevelForFileFailure"
}))
#Html.HiddenFor(model => model.FileId)
The problem here is the UpdateTargetId:-
My model currently doesnot have FileId value.
I am setting the value of Hidden field by jquery method and it works well.
$("#FileId").val(fileId);
But how can I set the same value in UpdateTargetId?
Thank You
If the value of this property is known only on the client side you could do that inside the OnSuccess callback. So get rid of the UpdateTargetId property from your AjaxOptions and then inside the editPrivilegeLevelForFileSuccess handler you could manually update the corresponding section:
function editPrivilegeLevelForFileSuccess(result) {
var fileId = $('#FileId').val();
$('#divFile-' + fileId).html(result);
}
Well, if you look how a form tag is produced from Ajax.BeginForm:
<form id="form0" action="/Redirects/Manage/List" method="post" novalidate="novalidate" data-ajax-update="#page" data-ajax-mode="replace" data-ajax="true">
You can use jquery to alter this, for example on OnChange event of a dropdown:
#Html.DropDownList("language", new SelectList(#Model.Locales, "Key", "Value"), new { onchange = "$(this.form).attr('data-ajax-update','#nowhere');$(this.form).submit();" }

Pressing an asp.net mvc Ajax.ActionLink with Insert into RenderBody() causes an endless loop

I have these ActionLinks in my Main Index View:
<p>#Ajax.ActionLink("Releases", "Index", "Release", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</p>
<p>#Ajax.ActionLink("Templates", "Index", "Template", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</p>
<p>#Ajax.ActionLink("Testplans", "Index", "Testplan", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</p>
below is this:
<div id="ContentPanel">
#RenderBody()
</div>
When I click each link Release,Templates, Testplans one after the other the switching of the views work.
When I click in this order:
Releases
Templates
Releases
Templates
The switching does not work anymore. The problem seems to be that when I set a breakpoint in my controller index method:
public ActionResult Index()
{
return View();
}
The Index Action is called in a looooooop ??
Why this?
Could you try this code:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";

Resources