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!
Related
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
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>
Because I am using Knockout in my view, I have set my form tag accordingly;
<form class="employeeListEditor" data-bind="submit: save">
However when I click the submit button, I want to do a partial page refresh. So how do I set the data-bind attribute in the Ajax.BeginForm?
This syntax does not work;
<% using (Ajax.BeginForm("GetCalendar", new AjaxOptions { UpdateTargetId = "siteRows" }, new { data-bind="submit: save", class="employeeListEditor" }))
{%>
You need to use unserscore (_) in your attribute name and the Ajax.BeginForm helper (in fact all the HTML helpers replaces unserscore with dashes in the given htmlAttributes object parameters) will be automatically replace it with a dash (-)
new { data_bind="submit: save", #class="employeeListEditor" }
And you need use an Ajax.BeginForm overload which accepts htmlAttributes like this one:
<% using (Ajax.BeginForm(
"GetCalendar", // actionName
null, // routeValues
new AjaxOptions { UpdateTargetId = "siteRows" }, // ajaxOptions
new { data_bind="submit: save", #class="employeeListEditor" } // htmlAttributes
))
{%>
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.
I have Ajax.ActionLink with htmlAttribute param
<%= Ajax.ActionLink("cool", "ViewCategory", new { id = elem.ID }, new AjaxOptions { UpdateTargetId = "score_" + elem.ID.ToString() }, new { myAttr = 123 } )%>
How can I read this attribute in controller method?
You can't.
All the htmlAttribute param does is instruct the generation of additional attributes to be added to the anchor html with it is sent to the client. These attributes are not included in the request when the anchor is clicked.
Place the attribute along side the id new {id = elem.ID, UpdateTargetID = ...} this should be included in the URL.