I'm struggling with a very basic feature. I want to refer another view from the current view to load the content from that view by applying very basic ajax. here is the code:
<div>
<ul id="biographies">
<li> Ajax</li>
<li> Index </li>
</ul>
<div id="biography">
The ajax content will appear here...
</div>
<script type="text/javascript">
$("#biography").load('Ajax.cshtml');
</script>
</div>
Both the page is in the same directory that is: views/home
Question 1: how to pass the parameter for load event?
Question 2: how to link to other pages using the anchor tag?
Thanks.
Use the Url.Action helper method:
$("#biography").load('#Url.Action("Ajax")');
Similarly, you can use Html.ActionLink to get an a tag for actions or routes:
#Html.ActionLink("Go to Index", "Index")
#Html.ActionLink("Go to Home:Index", "Index", "About")
The output will be like <a href='/About/Index'>Go to Home:Index</a>.
Remember, with MVC the idea is that URLs point to resources and routes, not to specific files. It's best to use these helper methods (rather than writing out hard-coded URLs) as they specify the route precisely.
Use Html.ActionLink to generate links and then use jquery for ajax loading. Off course, you need to write actions in controller for returning partial views. Jquery code: jsfiddle
Related
I am creating a dynamic user profile. I want to render partials using ajax (to avoid page reloads).
When I am rendering partial via ajax, for example Profile/sections/skills I am getting partial (my controller returns partial view) and rendering #partials div.
The problem is when I hit the route directly by manually typing in the browser Profile/sections/skills it returns only partial html.
I want both to work correctly: render partial via call with ajax and when I type in the url it can be found.
html
<div class="profile-navbar">
<ul class="ul-menu">
<li class="space"></li>
<li class="active"> <i class="fa fa-user"></i> About </li>
<li>
<a href="#" id="skills"> <i class="fa fa-robot"></i> Skills/a>
</li>
<li> <i class="fa fa-images"></i> Portfolio</li>
<li> <i class="fa fa-address-card"></i> CV</li>
<li> <i class="fa fa-briefcase"></i> Experience </li>
</ul>
</div>
<div id="partials"> </div>
js
$('.profile-navbar ul li a').click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("Skills", "Profile")',
type: "POST",
success: function (response, status) {
$("#partials").html(response);
}
});
});
Controller
[Route("Profile/Skills")]
public IActionResult Skills()
{
return PartialView("Skills");
}
You already have a partial view defined for your [Route("Profile/Skills")].
To accomplish what you want you need to do the following:
Define a regular view for the same route
This view will contain a reference to your partial so the partial is rendered within the larger HTML of the full view (when the route is called directly).
Modify Controller Action to check for Ajax
Once you have a regular view and the partial view then you can modify your controller action to conditionally decide whether to:
renderpartial (if the caller is Ajax)
or render the full view (if it is not an ajax call)
IsAjaxRequest() method
In past versions of ASP.NET MVC there was a method on the Request object called IsAjaxRequest(). When this method is available your controller action code could be as simple as:
[Route("Profile/Skills")]
public IActionResult Skills()
{
if (Request.IsAjaxRequest())
return PartialView("Skills");
else
return View();
}
ASP.NET Core is missing IsAjaxRequest() method
Unfortunately it seems that this method was overlooked in ASP.NET Core (as best as as I tell at the present time). But it also seems that the underlying code was simple enough that many people have managed to duplicate its behavior without much trouble.
If Request.IsAjaxRequest() is not available to you because of ASP.NET core you should be able to duplicate its behavior in your controller action something like this:
[Route("Profile/Skills")]
public IActionResult Skills()
{
bool isAjaxCall = Context.Request.Headers["x-requested-with"]=="XMLHttpRequest";
if (isAjaxCall)
return PartialView("Skills");
else
return View();
}
A more formalized and reusable approach to the dealing with missing IsAjaxRequest() method is described in this post
Is there is any link for Ajax helper tags documentation in Asp.net Core. I am trying to learn ajax with asp.net core but i found no documentation for it.
In asp.net mvc we use #Ajax.Form and then uses AjaxOptions method for work on ajax. After many hours search i found this link.
https://dotnetthoughts.net/jquery-unobtrusive-ajax-helpers-in-aspnet-core/
In this link there is a way work with ajax in asp.net core.
I implement it in my project and successful.
Then i search for its documentation but i found nothing.
I want its documentation link.Please anybody help for its documentation
There are no server-side helpers, like #Ajax.Form, in ASP.NET Core. You could probably write your own tag helpers for similar features but I haven’t seen anyone do this. The general idea is to write actual JavaScript when you want to have client-side behavior. Hiding these things behind server-side magic is usually not the best idea.
jquery-ajax-unobtrusive is a JavaScript package that adds client-side behavior to look for various attributes in the final rendered page to add functionality on top of your standard forms. So this would be a fully JavaScript-based solution.
Unfortunately, there does not seem to be documentation about it. You can take a look at its source code to figure out what may or may not be possible.
jquery-ajax-unobtrusive documentation
From taking a quick look at the source (disclaimer: without testing the functionality myself), this seems to be the supported data attributes and available functionality of the package:
data-ajax="true" – To enable the functionality for a form.
data-ajax-update – Selector for the elements that are updated with the AJAX result, using the mode.
data-ajax-mode
data-ajax-mode="before" – Prepends the data to the element.
data-ajax-mode="after" – Appends the data to the element.
data-ajax-mode="replace-with" – Replaces the element with the data.
Otherwise sets the HTML content of the element to the data.
data-ajax-confirm – Message that is displayed to the user to confirm the form submission.
data-ajax-loading – Selector of element that is shown while loading.
data-ajax-loading-duration (default: 0) – Animation duration for show/hide of the loading element.
data-ajax-method – Allows overwriting the HTTP method for the AJAX request.
data-ajax-url – Allows overwriting the URL for the AJAX request.
data-ajax-cache – Set to other value than "true" to disable the jQuery AJAX cache parameter.
data-ajax-begin – Callback function before the request starts (arguments: xhr)
data-ajax-complete – Callback function when the request is completed (arguments: xhr, status)
data-ajax-success – Callback function when the request was successful (arguments: data, status, xhr)
data-ajax-failure – Callback function when the request failed (arguments: xhr, status, error)
The callback functions are the equivalent of jQuery’s beforeSend, complete, success, and failure. From how it looks, you can specify the callbacks using a JavaScript object path to the function.
For example data-ajax-success="foo.bar.onSuccess" will call the function foo.bar.onSuccess(), i.e. it will look for an object foo in the window, get its bar member, and call onSuccess on that.
https://github.com/Behrouz-Goudarzi/AjaxTagHelper
AjaxTagHelper
A simple solution to using links and ajax forms using Tag Helper in aspnet core
First, copy the AjaxTagHelper class from the Extensions folder to your project.
Second, copy the AjaxTagHelper.js file from js folder in wwwroot and add it to your project.
Then do the following: Open the viewImports file and add the following code
#using AjaxTagHelper.Extensions
#using AjaxTagHelper
#using AjaxTagHelper.Models
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, AjaxTagHelper
To use Action Ajax, add the following code instead of the tag.
<ajax-action ajax-action="Delete" ajax-controller="Home" ajax-data-id="#Model.Id"
class="btn btn-danger btn-sm" ajax-success-func="SuccessDelete">
Delete
</ajax-action>
Use the following code to use AJAX to send the form to server.
<div class="row">
<form id="frmCreate" class="col-sm-9">
<div class="row">
<div class="col-sm-4 form-control">
<input placeholder="Enter Name" name="Name" class="input-group" type="text" />
</div>
<div class="col-sm-4 form-control">
<input placeholder="Enter Family" name="Family" class="input-group" type="text" />
</div>
<div class="col-sm-4 form-control">
<input placeholder="Enter Email#site.com " name="Email" class="input-group" type="email" />
</div>
</div>
</form>
<div class="col-sm-3">
<ajax-button ajax-controller="Home" ajax-action="Create" ajax-form-id="frmCreate" ajax-success-func="SuccessCreate"
class="btn btn-sm btn-success">
Create
</ajax-button>
</div>
</div>
Finally, add the scripts you need to view it, check the code below
<script>
function SuccessCreate(data) {
console.log(data);
$("#tbodyPerson").append(data);
}
function SuccessDelete(data) {
$("#tr" + data.id).fadeOut();
}
</script>
<script src="~/js/AjaxHelper.js"></script>
If you're looking for the old style Ajax helpers in Core, this Nuget package might help -
AspNetCore.Unobtrusive.Ajax
You can install it using -
PM> Install-Package AspNetCore.Unobtrusive.Ajax
This will enable you to use helpers like
#Html.AjaxActionLink()
#Html.AjaxBeginForm()
#Html.AjaxRouteLink()
Here's the github details. You can find more documentation in there.
Github Url to the project
I want to use #Url.Action to pass multiple parameters through the URL in an ASP.NET Core 2.0 Razor Page. I don't know which tag helper I should use.
#model Memberships.Models.SmallButton
<a asp-page="#Url.Action(Model.Action)#Model.ActionParameters"
class="btn #Model.ButtonType btn-sm">
<span class="glyphicon glyphicon-#Model.Glyph"></span>
<span class="sr-only">#Model.Text</span>
</a>
As far as I know you cannot do that with AnchorTagHelper. If you want to add parameters to it then you have to do this one by one:
<a asp-action="Edit" asp-route-id="#Model.Id" asp-route-something="Something">Link</a>
If you want to use Url.Action then you have to pass it via href parameter:
Link
You can use UrlHelper.Action(string action, object values) to pass additional route values:
Link
Is there anyway I can do the following code in razor?
<div>
<c:import url="http://hostName/HTML-file-name/" />
</div>
I would like to pull HTML from a given location and render it on a page. This should be possible...
Hope this makes sense...
In Razor, no. In HTML yes:
<div>
<iframe src="http://hostName/HTML-file-name/"></iframe>
</div>
Well actually you could use server side code to send an HTTP request to the remote resource and display the result inline:
<div>
#Html.Raw(new System.Net.WebClient().DownloadString("http://hostName/HTML-file-name/"))
</div>
But bear in mind that this will fetch only the content situated on the specified address. If this is for example an HTML page referencing external CSS, and javascript files, they will not be retrieved.
I am currently using <a> tag to click and navaigate as mentioned in below code.I want to navigate the below code in c# tag in page_prerender event based on id selected.could any one help on this?
<li>Category 1</li>
<li>Category 2</li>
<div id="cat1">
Content goes here
</div>
<div id="cat2">
Content goes here
</div>
something like if url doesn't contain '#' then
Response.Redirect("www.yoururl.com/Default.aspx#Cat2");
is that what you're looking for?
clicking on the <a> in html is really the same as just adding #Cat2 to the end of the URL , the browser knows what to do from there
I believe you need a url rewriting layer for how you have it. The <a> links are simply going to be a GET request with no further information. And even then you would need the links to be href="cat1" or href="#cat1".
The simplest alternative would be using <asp:linkbutton /> which can have server-side onclick events.
You might also look into AJAX requests, or use javascript to hide and display the sections, if the content is dynamic based on the request AJAX would be required there.