MVC Ajax.Beginform OnComplete/OnSuccess fired before controller call - asp.net-mvc

I'm trying to clear an ajax form after an item has been added to the database however the OnComplete and OnSuccess AjaxOptions get called before the form is submitted. How can I get it so the form is submitted first and the the OnComplete is called.
<% using (Ajax.BeginForm("AddTable", new AjaxOptions
{
UpdateTargetId = "tables",
InsertionMode = InsertionMode.InsertAfter,
OnComplete = "ClearForm()"
}))
{%>
which calls
function ClearForm() {
$('#DisplayName').val('');
}
However the DisplayName textbox is cleared before the balue is sent to the controller the form submits to. Is there a way around this.

OnComplete = "ClearForm()" should be called without the parentheses, i.e. OnComplete = "ClearForm". I can't say for sure that it would fix your issue though.

Related

How to avoid page refresh in asp.net mvc

without refresh
When I click on any page link of the partial view, that related page should be displayed in the render body part without any page refresh. How can I do that ?
You can use the AJAX helper that is used in conjunction with unobtrusive ajax
You can find more information at this page
Install Microsoft.jQuery.Unobtrusive.Ajax NuGet package
Include the script on _Layout <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
You then use the HTML Helper with specific options
Code Sample
#Ajax.ActionLink("View All Student Info", "AllStudent", "Home", new AjaxOptions
{
UpdateTargetId = "divAllStudent",
OnBegin = "fnOnBegin",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
LoadingElementId = "imgloader",
OnSuccess= "fnSuccess",
Confirm="Do you want to get all student info ?????"
},
new { #class = "btn btn-default" })
Then in the controller add a specific [GET] Route (WebAPI)
Code Sample
[HttpGet]
public PartialViewResult AllStudent()
{
using (TempEntities db = new TempEntities())
{
var objAllStudent = db.StudentInfoes.ToList();
return PartialView("AllStudent", objAllStudent);
}
}
The options UpdateTargetId is the HTML ID container of where the AJAX result will put the result content. Usually you want to use Replace. You can use OnBegin and OnSuccess as Javascript methods that do things like show loaders, hide loaders, etc etc

ASP.NET MVC Ajax ActionLink ActionName vs AjaxOptions URL difference?

See this simple Razor markup:
#Ajax.ActionLink("Load something", "LoadPartialView", new AjaxOptions
{
UpdateTargetId = "here",
LoadingElementId = "loading",
OnBegin = "show_loading",
OnComplete = "hide_loading",
Url = "/Home/LoadPartialView2"
})
I notice if I include LoadPartialView as a parameter in the ActionLink and also specify a URL LoadPartialView2 in AjaxOptions, the generated link will invoke the LoadPartialView2 action. The optional Url takes priority:
If Url was removed, then clicking the link will invoke
LoadPartialView.
If ActionName parameter was set to null, vice versa,
LoadPartialView2 will be invoked.
When would the URL in AjaxOptions be used over ActionName?
I noticed if I set Url to http://www.google.co.uk it doesn't load the page into the div tag (id="here").
Thanks!

Correctly using quote marks in MVC view Razor

I am having some difficulties using quote marks in ASP.Net Razer view as I keep ending up with them replaced with '
If I for example type:
#{string test = "String 'with' quotes"}
#test
I end up with:
String 'with' quotes
In the above example this is desirable.
However, take this second example:
#{string myJSFunction = myJSFunction('myString')"}
#myJSFunction
I end up with:
myJSFunction('myString')
Which results in a broken javascript function.
I have tried excaping the quote marks with \, but they don't seem to be having any effect.
Here is the actual problem I am faced with:
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = #myJSFunction
}))
Any advice?
The # operator always HTML-encodes strings. If you want the raw string value, use #Html.Raw(myJSFunction).
In razor, # will encode and render. Try Html.Raw method. This method returns markup that is not HTML encoded.
#Html.Raw(myJSFunction)
So if you want to execute the function in a script block, you can do it like
#{string myJSFunction = "alert('Rise and Shine')";}
<script type="text/javascript">
#Html.Raw(myJSFunction)
</script>
The solution to your issue is already mentioned (Html.Raw()) but I'm not sure why you're using # in your code sample given. From the looks of it you're already in code block when you try to assign it, so why use the razor.
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = #myJSFunction
}))
should be
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = myJSFunction
}))
# is what tells the StreamWriter for the page to write the result to the response, and as such is intended to be injected into the page after HtmlEncoding. Using Html.Raw bypasses the Html encoding aspect but in your case you're not writing it the page directly yourself, you're letting Html.BeginForm handle that, so you don't need the # in the assignment of your OnComplete function.
UPDATE: Ok, another thing I forgot to mention is that the methods passed to the AjaxOptions are Javascript functions only, no parameters by the looks of it. Parameters are passed in automatically by the Unobtrusive scripts that handle all the wiring. So your form should look like this...
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = "myJSFunction"
}))
And it will handle the rest. If you need to pass additional parameters in the myJSFunction function, you're probably going to have to expose them via other means. Either as a javascript variable or by associating it with some other element and access it using $("elementselector").data("dataAttributeName") (this is my preferred and suggested method). One of the common requested modifications made to the unobtrusive ajax JavaScript libraries (I wish Microsoft would just adopt this change and be done with it) is to set the context of this to the element that triggered the ajax event. So for in this case it would make this equal to the form element. With all this in mind, here's my recommendation.
First:
Modify your Unobtrusive Ajax script file so that the source element gets assigned to the this keyword so that's it's available in your JavaScript handling the unobtrusive events.
This question outlines what it involves (one line added to the file)
Second:
Add your string to one of the data attributes on your form
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new {id = ViewBag.InputResourceID},
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = "myJSFunction"
},
new { data_parameter_name = "myString" }))
Third:
Access your parameter from inside of the javascriptfunction handling your event.
<script>
function myJSFunction(data, textStatus, jqXHR)
{
//data, textStatus and jqXHR are set for you by the unobtrusive ajax script file automatically, feel free to use them
var parameter = $(this).data("parameterName");
alert(parameter);
}
</script>

ActionLink called only once in IE

I have an MVC blog app that makes a call to Ajax for updating a flag.
In IE (and only in IE, in other browsers it runs fine), I can call an ActionLink only once. If I click after the first time, the ajax action in the controller is not invoked.
Here is the partial part of code of the View:
<div id="news_comment_state_#(Model.Id)">#(Model.FlControlled==false?"Da approvare":#Model.FlApproved?"Approvato":"Respinto")</div>
#Ajax.ActionLink("Approva", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = true }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+#Model.Id})
<br />
#Ajax.ActionLink("Respingi", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = false }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+#Model.Id})
If I put a breakpoint in the controller it is fired only once per Link, then it is never called again. Where is the error? Maybe cache problem?
Another way to avoid the caching problem is to add the following to the line above your method in the controller:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult MyMethod() {
...
}
This will make sure it runs the server-side code.
Sounds like cache. Add a random integer to the end to make sure you get a fresh request.

Append row to <TABLE> using Ajax.BeginForm()

I have an HTML <TABLE> displaying a list of items in the rows of the table. To add a new item to the list of items I have a form which submits the data to my controller via AJAX using Ajax.BeginForm. Once the action on the controller has finished it returns a partial view containing the markup for a new row to append to my table (eg. <TR><TD>.......</TD></TR>). My question is how do I add the new row my existing table?
I have create an at the top of the as my header with the id "userrightsgridheader" and specified my Ajax.BeginForm as follows:
<% using (Ajax.BeginForm(
"CreateUserRight",
new { workstationId = Model.Id },
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "userrightsgridheader"
}
))
{ %>
The problem is that this does not work. Does anyone have any ideas on how to achieve this?
Thanks!
You can add the following AjaxOption, this executes 'jsfunction' when the Ajax functionality executed successfully:
new AjaxOptions { OnSuccess = "jsfunction" };
You can add the tablerow in the jsfunction.
update
you can define jsfunction as follows:
function jsfunction(ajaxContext) {
//ajaxContext contains the responseText
}
AjaxContext is defined as follows:
AjaxContext ajaxContext = new AjaxContext(request, updateElement, loadingElement, ajaxOptions.InsertionMode);

Resources