Set UpdateTargetId dynamically or change UpdateTargetId - asp.net-mvc-3

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

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

MVC Multiple Ajax Calls

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

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>

MVC3 - Ajax loading icon

I would like to show an AJAX loading icon during an ActionResult request that can take a few seconds to process.
What is the best approach to accomplished this?
I only want to display the icon after the built it validation passes (I am using MVC3, EF Code First, so the validation is automatically put on the page).
There may be further validation/exceptions during the ActionResult, in which case a message is displayed to the user, and I'd then want the loading icon to disappear again.
Define your link as an Ajax action link and specify the ID of a spinning GIF somewhere on your page.
<div id="result"></div>
<img id="spinner" src="../content/ajaxspinner.gif" style="display: none;">
#Ajax.ActionLink("Link Text", "ActionName", "ControllerName", null, new AjaxOptions{UpdateTargetId = "result", LoadingElementId = "spinner"}, null)
or if it is a form:
#using(Ajax.BeginForm("Action", "Controller", null, new AjaxOptions{UpdateTargetId = "result", LoadingElementId = "spinner"}, null))
{
#Html.TextBox("Data")<br/>
<input type="submit" value="Submit" />
}
Put the image in a div tag like this:
<div id="busydiv" style="display:none;"><img src="busything.gif" /></div>
and then create your link like this:
#Ajax.ActionLink("Link Text", "ActionName", "ControllerName", null, new AjaxOptions { LoadingElementDuration = 1000, LoadingElementId = "busyDiv", HttpMethod = "Post", UpdateTargetId = "targetDiv", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }, null)
or in a form do this:
#using (Ajax.BeginForm("TestAjax", new AjaxOptions { LoadingElementDuration=1000, LoadingElementId="dave", HttpMethod = "Post", UpdateTargetId = "targetDiv", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }))
Obviously omitting those AjaxOptions that you don't need, as per the documentation here: http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.aspx
Just my two cents:
The solution posted by Chris is valid and will work BUT you must add a reference to the two javascript libraries below. Please note that the order matters:
<script src="~/scripts/jquery-1.8.0.js"></script>
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>
When you create an MVC application pre-loaded with bundling and all these nu-get packages this will probably not be a problem for you but if you were like me and created an empty ASP.NET MVC application you might run into issues.

Resources