Ajax.ActionLink does not work when OnBegin is true - ajax

I intend to call function when clicked on ActionLink and depending on the ouptput of the function would either go the next page or show alert.
When OnBegin is true in Ajax.ActionLink, it should hit the controller method and hence go to specified view. But when I click on the ActionLink, OnBegin returns true but nothing happens. I see the same page.
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (#Html.BeginForm())
{
#Ajax.ActionLink("Add Document", // <-- Text to display
"AddDocument", // <-- Action Method Name
"Home", // <-- Controller Name
null,
new AjaxOptions { OnBegin = "OnBegin('AddDocument')" },
null
)
}
<script type="text/javascript">
function OnBegin(vObject) {
debugger;
return true;
}
</script>
Any help would be appreciated.
Thanks.

I think that you are using it in the wrong way. #Ajax.ActionLink will hit your controller and retrieve the content of the response but you haven't set any space to hold the response. One of the properties of AjaxOptions is UpdateTargetId which should be setted to the id tag that will hold the response.
#Ajax.ActionLink("Add Document", "AddDocument", "Home",
new AjaxOptions
{
OnBegin = "OnBegin('AddDocument')",
UpdateTargetId = "responseContent"
})
In the view put a tag to hold the response:
<div id="responseContent"></div>
The response will be inserted inside the div.

Related

AjaxOptions OnComplete

I wanted to use OnComplete, since I needed to modify the view before it was updated with the data from the Ajax call. As it says here: MSDN, it should be pretty straight forward.
However, it didn't work and after some investigation it seems that OnComplete fires before OnSucess but after the view is updated.
Code used for testing:
#{
AjaxOptions options = new AjaxOptions {OnSuccess = "onSuccess",
OnComplete = "onComplete", UpdateTargetId = "Update"};
}
#Ajax.ActionLink("Hit it", "Action", options)
<div id="Update"></div>
<script type="text/javascript">
function onSuccess() {
alert('onSuccess: ' + $('#Update').html());
}
function onComplete() {
alert('onComplete ' + $('#Update').html());
}
</script>
public ContentResult Action()
{
return Content("Content");
}
Am I missing something here or what's up?
Try this in your View:
#Ajax.ActionLink("Hit it", "Action", new AjaxOptions() { OnSuccess="done"} )
<div id="Update"></div>
Controller Action:
public ContentResult Action()
{
return Json(new { content="content" }, JsonRequestBehavior.AllowGet);
}
JavaScript:
function done(data) {
var message = data;
if (typeof message["content"] !== "undefined") {
$('#Update').html(message["content"]);
} else {
alert("error");
}
}
You can pass a Json result from your Controller and get that message in your View via JavaScript and update your div.
The issue is that the UpdateTargetId is actioned before the OnSuccess handler is triggered.
If you want to to update the view before or perform extra steps before the content is updated, then remove the updatetargetid from the AjaxOptions and handle the update yourself in the OnSuccess handler. You will get full control over when the view is updated then.
function onSuccess(result, status, xhr)
{
// put in your view update code here.
// and then
$("#Update").html(result);
}
OnComplete is fired when ajax call completed and response data has been instantiated but page has not yet updated

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>

How to show a partial view on click of actionlink in mvc

I have the following two action links on a page:
#Html.ActionLink("User List","list");
#Html.ActionLink("Admin List","admin");
On their click I want to show/hide a partial view using jQuery. Help me with solution for this.
You could use the Ajax.ActionLink helper instead:
#Ajax.ActionLink("User List","list", new AjaxOptions { UpdateTargetId = "someDiv" });
#Ajax.ActionLink("Admin List","admin", new AjaxOptions { UpdateTargetId = "someDiv" });
This assumes that the list and admin actions return partial views:
public ActionResult List()
{
return PartialView();
}
and the result of this partial view will be injected into a DOM element with id="someDiv". Also for this to work don't forget to include the jquery.unobtrusive-ajax.js script to your page
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<div id="test"></div>
#Ajax.ActionLink("User List","list", new AjaxOptions{ UpdateTargetId = "test" });
#Ajax.ActionLink("Admin List","admin", new AjaxOptions{ UpdateTargetId = "test" });

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

Close modal window containing ASP MVC Ajax form

in a webapp I'm using an ASP MVC Ajax form in a modal window. I do not use any specific jQuery code, only some to open the modal window (i.e. showModal() function):
#Ajax.ActionLink("Open", "Add", "Home", new {id = Model.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "modal", OnSuccess = "showModal()"})
This code loads my form (partial view) into a div and opens it as a modal window. In the form submit ActionResult I just use the default ModelState object to validate it, and in case of an error I return the same partial view containing model errors. This works fine except for the following situation: when the model contains no errors I want to auto-close the modal window. I tried the following:
#using (Ajax.BeginForm("Save", "Home", new AjaxOptions {HttpMethod = "POST", UpdateTargetId = "modal", OnSuccess = "hideModal(); alert('Saved');"}))
However, when the model contains errors the Ajax call is still valid, so OnSuccess will be called. I tried to solve this by sending an error HttpStatusCode in the partial view, but then the div is not updated with the new html.
I think the only solution is sending a partial view containing javascript code that closes the modal window when the model contains no errors, but this solution is not very neat in my opinion. Any other ideas?
I just had to do the same thing today. The solution I came up with was to return a JsonResult with a property set to true when the action succeeded. In the OnSuccess callback of the AjaxOptions I checked for the property and closed my modal window.
Controller Method
[HttpPost]
public ActionResult Hold(JobStatusNoteViewModel model)
{
if (ModelState.IsValid)
{
//do work
return Json(new {success = true});
}
return PartialView("JobStatusNote", model);
}
PartialView
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "JobStatusForm", OnSuccess = "closePopUp" })) { %>
<div id="JobStatusForm">
<!-- Form -->
</div>
<% } %>
<script>
function closePopUp(data) {
if (data.success) {
//close popup
}
}
</script>

Resources