How to avoid page refresh in asp.net mvc - 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

Related

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!

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

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>

Ajax.Actionlink, partial and webgrid issue

I have the following issue.
My url structure is like this:
/people/edit/usercode
In my controller i have the following:
[AcceptVerbs(HttpVerbs.Post)]
public PartialViewResult LoanRefresh(string id)
{
PeopleModel p = new PeopleModel();
return PartialView("_LoanHistory", p.getPersonLoanHistory(id));
}
In my view i have:
#Ajax.ActionLink("Refresh", "LoanRefresh", new { id = Model.IdentityCode }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "loanHistory", LoadingElementId = "Loading" }, new { #class = "button" })
and
<div id="loanHistory">
#Html.Partial("_LoanHistory", Model.Loans)
</div>
When run the Ajax.ActionLink it gets the data back ok and it updates the div, but the url of the sort links on the webgrid then change their address to:
/People/LoanRefresh/AFU0006?sort=CreatedOn&sortdir=ASC
i need to stay as:
/People/Edit/AFU0006?sort=CreatedOn&sortdir=ASC
Any help would be greatly appreciated.
Well #Nick, that's because your action name is LoanRefresh and not Refresh. To do that you will probably have to do some routing or even redirect your LoanRefresh results to an action named Refresh.
Try setting ajaxUpdateContainerId to an object that is specified in the partial view, rather than an object in the view from which the partial view is originally called. The sort URLs should work correctly then.

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