Using Razor Pages coredotnet how can I load a partial view via ajax - ajax

In using Razor pages, it is simple to use partial using #Html.Partial(..).
However, when a drop down changes, I want to refresh part of the view - the part rendered by the partial view.
I have searched lots, and found answers such as: https://github.com/aspnet/Razor/issues/2073 where they say partials are meant for code behind.
Is there a reasonable workaround such that I can re-render a subset of the view which is defined in a partial view? What is the best practice way of achieving this?

Yes,
Have an action method that can be called to reload just the partial view:
public ActionResult Reload()
{
return PartialView("NameOfPartialView");
}
Get it from the client (I'll use jQuery):
$.ajax({
type: "post",
url: "Reload",
data: {},
success: function(d) {
//d is the HTML content returned from the Action Method
$("#parentelementaroundinnerdata").html(d);
}
});
Returning the partial view from the action method returns an HTML string, and that can be injected into the page using a parent element to replace its contents with the update. That means when rendering the original, have the setup as the following:
<div id="parentelementaroundinnerdata">
#Html.Partial("NameOfPartialView")
</div>
You can use the same partial from an AJAX request and for loading an initial result - sometimes you have to be careful within the partial on what is going on because of that though...

Related

Asp MVC AjaxExtensions, call from controller

I'm sure this is simple but I'm struggling to find it
Inside a controller you can do something like this:
public ActionResult MyAction()
{
string url = Url.Action(action, controller),
// do something with the url
}
What's the Ajax equivalent? i.e. where you would call Ajax.ActionLink in a View whats the equivalent for the controller?
Elaboration-
I have a master/detail arrangement with a grid and some input elements. You can click on select/delete in the grid to amend or delete the line.
The grid is a Kendo UI grid, the view is rendered via:
a partial view to render the input elements
creating a json object, i.e.
#{
var jsLines = #Html.Raw(Json.Encode(Model.Lines));
}
Binding the Kendo grid to this json
From within the grid I want to hit on select and call an Ajax method to update the partial view with the form details
thanks
You can use Url.Action from the razor view. Something like :
$.ajax({
url: '#Url.Action("Action", "Controller")',
...
I'm not at all convinced that this is the right way to go but it's always good to have options.
Ajax.ActionLink seems to be the same as Url.Action but with a few attributes thrown in. So you can use this:
return string.Format("<a data-ajax='true' data-ajax-mode='replace'
data-ajax-update='{2}' href=\"{0}\">{1}</a>",
Url.Action(action, controller, routeValues),
text,
"formContainerSelectSection");
to update this:
<div id="formContainerSelectSection">
... stuff to be replaced via ajax
</div>
I accept, especially after the discussion with NicoD, that there are other and probably easier ways to do this, in particular this is creating a link in the controller, that's the Views job, but the original question was about how to do this

Poplate View with new updated Model in success function of $.ajax

I am making an ajax call to controller to post data from view to controller.And in the receiving controller I am updating my model with new values.Now I want to bind this new model to view again in success call of $.ajax post.Please Suggest.
one way to do this is to return a partial view from the controller. You can replace the contents of your previous view with the new html content. Lets expand on this...
so, here is your controller action
[HttpPost]
public ActionResult SomeMethod(params...){
....
var model = some model;
...
return PartialView("ViewName",model);
}
and in the ajax, use
$.ajax({
url : #Url.Create("Action","Controller"),
type : 'POST',
data: { ... your data params ..},
success : function(result){
$("#ContainerId").html(result);
}
})
in the html you would need a div with the id = "ContainerId". The content would get swapped out by the html passed back in the success function.
The Model is only used in RAZOR when rendering the page. Once you get to the point where you are using AJAX, the model is no longer available to you.
What, exactly, are you trying to accomplish? Maybe there is another way to do it?

How do I render a view after POSTing data via AJAX?

I've built an app that works, and uses forms to submit data. Once submitted, the view then redirects back to display the change. Cool. Django 101. Now, instead of using forms, I'm using Ajax to submit the data via a POST call. This successfully saves the data to the database.
Now, the difficult (or maybe not, just hard to find) part is whether or not it's possible to tell Django to add the new item that has been submitted (via Ajax) to the current page, without a page refresh. At the moment, my app saves the data, and the item shows up on the page after a refresh, but this obviously isn't the required result.
If possible, I'd like to use exactly the same view and templates I'm using at the moment - essentially I'd like to know if there's a way to replace a normal HTTP request (which causes page refresh) with an Ajax call, and get the same result (using jQuery). I've hacked away at this for most of today, so any help would be appreciated, before I pull all of my hair out.
I had a very similar issue and this is how I got it working...
in views.py
from django.utils import simplejson
...
ctx = {some data to be returned to the page}
if ajax == True:
return HttpResponse(simplejson.dumps(ctx), mimetype='json')
then in the javascript
jQuery.ajax({
target: '#id_to_be_updated',
type: "POST",
url: "/",
dataType: 'json',
contentType: "text/javascript; charset=\"utf-8\"",
data: {
'foo':foo,
'bar':bar,
},
success: function(data){
$("#id_to_be_updated").append(data.foo);
}
});
Here's how I did it:
The page that has the form includes the form like so
contact.html
{% include "contact_form.html" %}
This way it's reusable.
Next I setup my view code (this view code assumes the contact form needs to be save to the db, hence the CreateView):
class ContactView(CreateView):
http_method_names = ['post']
template_name = "contact_form.html"
form_class = ContactForm
success_url = "contact_form_succes.html"
There are a few things to note here,
This view only accepts pots methods, because the form will be received through the contact.html page. For this view I've setup another template which is what we included in contact.html, the bare form.
contact_form.html
<form method="POST" action="/contact">{% crsf_token %}
{{ form.as_p }}
</form>
Now add the javascript to the contact.html page:
$("body").on("submit", 'form', function(event) {
event.preventDefault();
$("#contact").load($(this).attr("action"),
$(this).serializeArray(),
function(responseText, responseStatus) {
// response callback
});
});
This POSTS the form to the ContactView and replaces whatever is in between #contact, which is our form. You could not use jquery's .load function to achieve some what more fancy replacement of the html.
This code is based on an existing working project, but slightly modified to make explaining what happens easier.

How to Call an Action from a View and return its result?

I have defined an action on my controller which accepts an integer and returns a string value:
public string SqlQuery(int listItemId)
{
return _sqlListSharePointList.GetSqlQueryFromCache(listItemId);
}
How could I call this action from my view? also what other options do I have apart from AJAX?
I tried the below but didn't work:
$.get('/SqlReportList/SqlQuery', 1, function (data) {
alert(data);
});
the "SqlReportList" is the name of my controller.
I also tried the below code:
$.get('/SqlReportList/SqlQuery/1', function (data) {
alert(data);
});
But it threw an exception on production that the listItemId is null.
Should I decorate my Action differently?
I also tried accessing it via fully qualified name but same error:
http://localhost:4574/SqlReportList/SqlQuery/1
Thanks,
If you do not want to use ajax (which is recommended) then only way to call the method is thru page refresh, only that way you are hitting your server side (controller) again from the view.
$.get('/SqlReportList/SqlQuery', { "listItemId": listItemId }, function (data) {
$('#tbSqlQuery').text(data); }
);
Is the parameter known at the time of rendering the surrounding page?
If so (and I've understood your question correctly) then you can use Html.RenderAction. See http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx
If not, then you can only really use AJAX or a full page reload. For getting the URL right for AJAX, you should be able to use Url.Action with some placeholder value.
The T4MVC project offers strongly-typed support for various things including action URLs, even supporting explicit placeholders for Javascript code. See section 2.2.2 of http://t4mvc.codeplex.com/documentation

How do you build a Single Page Interface in ASP.NET MVC?

I want to build a webapplication with a "Single Page Interface", using ASP.NET MVC.
I have searched if this was at least possible and I think the answer is: not by simple means (reading http://msdn.microsoft.com/en-us/magazine/cc507641.aspx#S2 second-last paragraph; that article is from May 2008, though).
I found other examples which implemented this by coding/hacking with jQuery. However, I'm looking for a clean solution, using standard .NET approaches, if possible.
What I want is precisely the same functionality when you create a new "MVC Web Application". However, instead of links to "/Home/About" which reloads the entire page, I want links to "#Home/About" which loads only the new part via AJAX.
The standard approach of calling templates (partial views) with Html.RenderPartial is exactly what I want, only then loading them in through AJAX-requests.
Of course, it might be that I can't use these templates that are rendered by the Master-page for some reason (maybe it's expecting to always be called in a certain context from a certain place or so). But maybe there's another clean solution for how to build your template-pages and fetching them from the Master-page.
Who has a nice solution for implementing such thing, a Single Page Interface?
PS: I'm developing in Visual Web Developer 2008 Express Edition with MVC 1.0 installed, in C#
[edit]
Below I read that working with the templates is possible and that jQuery looks indeed like inevitable, so I tested it.
The following code transforms regular links created by Html.ActionLink into anchor-links (with #) to contain history, and then fetch the page via AJAX and only injecting the html-part I'm interested in (i.e. the partial page inside div#partialView):
$("a").each(function() {
$(this).click(function() {
$("div#partialView").load($(this).attr("href") + " div#partialView");
location.hash = $(this).attr("href");
return false;
});
});
These links also allow for graceful degredation.
But what I have left now, is still fetching the whole page instead of only the partial page. Altering the controller didn't help; it still provided me html of the whole page, with all of these statements:
public ActionResult About()
{
return View();
return View("About");
return PartialView();
return PartialView("About");
}
How could I only return the content of the part I'm interested in (i.e. the contents of Home/About.aspx)?
What I'd like is POSTing a value with AJAX (e.g. "requesttype=ajax") so that my controller knows the page is fetched via AJAX and only returns the partial page; otherwise it will return the whole page (i.e. when you visit /Home/About instead of #Home/About).
Is a good practice to alter Global.asax.cs maybe, to create a new routing schema for AJAX-calls, which will only return partial pages? (I haven't looked into this much, yet.)
[edit2]
Robert Koritnik was right: I also needed an About.ascx page (UserControl) with only the small HTML-content of that page. The first line of About.aspx was linked with the Master-page via MasterPageFile="~/..../Site.master" which caused that all HTML was printed.
But to be able to execute the following in my controller:
public ActionResult About()
{
return Request.IsAjaxRequest() ? (ActionResult)PartialView() : View();
}
I needed to alter the way a PartialView (.ascx file) and a View (.aspx) file was found, otherwise both methods would return the same page (About.aspx, ultimately resulting in an infinite loop).
After putting the following in Global.asax.cs, the correct pages will be returned with PartialView() and View():
protected void Application_Start()
{
foreach (WebFormViewEngine engine in ViewEngines.Engines.Where(c => c is WebFormViewEngine))
{
/* Normal search order:
new string[] { "~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Views/Shared/{0}.aspx"
"~/Views/Shared/{0}.ascx"
};
*/
// PartialViews match with .ascx files
engine.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx" };
// Views match with .aspx files
engine.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx" };
}
RegisterRoutes(RouteTable.Routes);
}
Full view vs. Partial view
Seems like you've messed up something. If you create an About.aspx page with all the HTML needed to display the whole page it doesn't really matter if you say
return PartialView('About');
The view still returns all the HTML that's written in it.
You should create a separate About.ascx that will only have the content of the page itself without the header and other stuff that's part of the whole page.
Your original page About.aspx will have something like this in its content (to avoid repeating writing the same content twice):
<%= Html.RenderPartial("About") %>
And you can have two controller actions. One that returns a regular view and one that returns a partial view:
return View("About"); // returns About.aspx that holds the content of the About.ascx as well
return PartialView("About"); // only returns the partial About.ascx
Regarding routes in Global.asax
Instead of writing separate routes for Ajax calls you'd rather write an action filter that will work similar as AcceptVerbsAttribute action filter. This way your requests from the client would stay the same (and thus preventing the user from manually requesting wrong stuff), but depending on the request type the correct controller action will get executed.
Well, you can load Partial View through AJAX request. In example, I'll use jquery to make an ajax call.
These could be the action in controller (named HomeController):
public ActionResult About()
{
//Do some logic...
//AboutView is the name of your partial view
return View("AboutView");
}
JQuery ajax call to place the retured html in place you want:
var resultDiv = $('#contentDIV');
$.ajax({
type: "POST",
url: "/Home/About",
success: function(responseHTML) {
resultDiv.replaceWith(responseHTML);
}
});
[edit-question is updated]
It is possible to do exactly what you want. First controller action can give you back the partial view, so mine "AboutView" could have been something like this:
<table>
<tr>
<th>
Column1Header
</th>
<th>
Column2Header
</th>
</tr>
<tr>
<td>
...
</td>
<td>
...
</td>
</tr>
and this HTML is exactly what are you going to have in responseHTML on success handler in jquery ajax method.
Second, you can distinguish in controller action if the request is an ajax request:
public ActionResult About()
{
//partial AboutView is returned if request is ajax
if (Request.IsAjaxRequest())
return View("AboutView");
else //else it will be the default view (page) for this action: "About"
return View();
}
We've got a site that does exactly this, and you really want to use the jQuery route here--alot easier to implement in the long run. And you can easily make it gracefully degrade for users who don't have javascript enabled--like google.
it isn't all that clear what are you asking for, is it for a complete example or for some specific functionality? You should be able to do this without JQuery for simple scenarios, you can use the Ajax view helpers like the ActionLink method. Also, I don't really understand what is your issue with RenderPartial, but maybe you're looking for something like RenderAction from ASP.NET MVC Futures.
ASP.NET MVC 4 (now in beta) adds support for Single Page Applications in MVC.
http://www.asp.net/single-page-application
UPDATE:
...and they removed it from the MVC 4 RC
UPDATE:
...and it is back with the 2012 Fall update

Resources