I have a simple page displaying thumbnail list ,
I want to to add a pager , i have added two action links
<li class="ui-pagination-next">#Html.ActionLink("Next", "Paginate", "Home", new { nbSkip = ViewBag.nextSkip }, null)</li>
when i click on the link i'm redirected to
http://localhost:41626/#/Home/Paginate?nbSkip=60
instead of
http://localhost:41626/Home/Paginate?nbSkip=60 ,
does anyone know why the '#' character is added to the URL ?
Route copnfig :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
by looking at your code i could find ui-pagination-next
this might mean that some other JS framework is actually listening to the click events of this link and doing some kind of ajax
hash "#" character is being used so that actually browser does not redirects to the page and at the same time maintains history
so if you press the browsers back button this additional peice of the link after # is removed and any JS framework subscribed to the evet knows how to handle it then
in simpler terms.
anything after the # in a url isnt sent to the server. Because some JS framework is handling the ajax part, it does not want that request should directly go to the server and also at the same time show look proper in the browsers address bar hence adds whatever you have in the link after the # and carries on with AJAX
heres an indepth article using hash for back and forward
From looking at your li class of ui-pagination-next im assuming jQuery Mobile is being used here.
jQuery Mobile by default, makes your links AJAX enabled
If you wish, you can prevent this by using:
$.mobile.ajaxLinksEnabled = false;
<script type="text/javascript">
$(function(){
$.mobile.ajaxLinksEnabled = false;
});
</script>
If i were you , I would use Ajax Raw ActionLink :
#Ajax.RawActionLink("NameofLink", "Action", "Controller", new { oid = 0, type = "oid and type are 2 parameters you want to send to action " }, new { id = "btnNewB", #class = "anyclass" })
Thank you all for your responses,
well seen #curt, in fact I'm using jQuery mobile, and what was causing the problem is mobile.changePage
Now I'm using simple button to navigate throw pages, but
$.mobile.ajaxLinksEnabled = false;
Does not resolve my problem with ajax link's. So I've done this, and it's working now
#Html.ActionLink("Previous", "Index", new { nbSkip = ViewBag.previousSkip }, new { data_role = "button", data_icon = "arrow-l", rel = "external", data_ajax = false })
Thanks #Parv Sharma for your explanation
Related
I have bellow link when the user click on it ,it should be load Article view that is in current area.
picture
But when I click on this link I get this error
but I've checked my routeconfig and my admin area and I have used namespases as well.
In my routeconfig
In my Admin area
I can not figure out what problem is ,I've used namespaces but it doesn't work.
when I click on this link <a href="/Article/Details/2">
I get the Error but my route config like these
In my routeconfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "IdentitySample.Controllers" }
);
And in Admin area config:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Administrator_default",
"Administrator/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "tadvinhesab.Areas.Administrator.Controllers" }
);
}
and I ended up with this link
<a href="#Url.Action("Details", "Article", new { Area = "IdentitySample",id = #article.id }, "https")">
but Area = "IdentitySample" cause the link dose not work when i put in new array.
And in another shot I changed it this way
link text
but my problem in still the same
looks like you forgot to change the namespace:
namespaces: new[] { "IdentitySample.Controllers" }
you should change it to something like this:
namespaces: new[] { "tadvinhesab.Controllers" }
also in this link, you can see a lot of other possible solutions to solve this:
Multiple types were found that match the controller named 'Home'
After a few hours working around, I finally realized that I use identity sample project that default namespace was identitySmaple but in some sections of my project I used my own namespace with a different names from identitySmaple that causes this weird problem.
with the help of (Ctrl+Shift+H), I replaced all identitySmaples to my namespace then It works properly.
I inherited some code and I am trying to figure the right url to a webapi controller but my knowledge of mvc web api is lacking.
I have inline script that is making an ajax post like this:
$('#saveNewEducation').on('click', function () {
var educationAdd = {
'educationId': $('#newEducation').val(),
'startDate': $('#newEducationDate').val(),
'identificationId': $('#identificationId').val(),
'educationNote': $('#newEducationNote').val(),
'examinerId': $('#newExaminer').val()
};
$.post('#Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)
.done(function (data, textStatus, jqXhr) {
if (jqXhr.status == 200) {
$('#save-education').modal('show');
} else {
$('#fail-save-employee').modal('show');
}
})
.fail(function (jqXhr) {
var education = $("#new-education");
if (jqXhr.status == 409) {
$('#future-save-employee').modal('show');
} else {
if (jqXhr.status == 400) {
clearErrors(education);
var validationErrors = $.parseJSON(jqXhr.responseText);
$.each(validationErrors.ModelState, function (i, ival) {
remoteErrors(education, i, ival);
});
} else {
$('fail-save-employee').modal('show');
}
}
});
I don't like inline script and I have created a seperate js file where I want to make this call from.
I need help with
I need help figuring out the right url to the api controller so that i can use it in the script file.
I tried
Reading this article I tried the following:
$.post('/DefaultApi/EmployeeApi', educationAdd)
This gave me a
404 not found error.
in the inline script the url is like this:
$.post('#Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)
WebApiConfig.cs file:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
method I am trying to access in EmployeeApi controller:
public IHttpActionResult EducationPost(EmployeeEducation model, string educationName){}
How can I do this?
Resolving the URL
Generally in MVC applications, you would resolve this by using the Url.Action() helper to resolve the proper URL provided its Controller, Action and RouteValues:
// Supply the Action, Controller and any route values that you need
$.post('#Url.Action("EducationPost","EmployeeApi", new { educationName = "educationCreate"})', function(){
// Do something here
});
However, Web API also features the Url.Link() helper that might be useful as well and works in a similar manner except based on the route itself :
$.post('#Url.Link("DefaultApi", new { controller = "EmployeeApi", action = "EductationPost", educationName = "educationCreate" })', function(){
// Do something here
});
When using External Javascript Files
As you would imagine, these techniques won't work when using external Javascript files. What I generally recommend in these situations is to consider using a data-* attribute in HTML to store the URL and then reference that within your event handler that will trigger the AJAX call :
<button id='call-ajax' data-post-url='#Url.Action(...)' />
<script>
$(function(){
$('#call-ajax').click(function(e){
// Read the attribute and use it
$.post($(this).attr('data-post-url'), function(){
// All done
});
});
});
</script>
You could obviously accomplish this same basic idea through the use of variables or hidden elements, but the same idea basically holds true as far as actually accessing it goes.
Have a look at this answer:
How to send razor created Url to js file
This user offers 3 possible solutions.
global js variable
custom "data-" attribute
hidden input
I have a search box on my page (.cshtml) with 3 drop down boxes (Country, State, City). When I click on Search button, the URL needs to be changed to like below.
http://localhost:1234/OrderHistory/Orders (default)
When I click on search with values in dropdowns, the url is to be changed to
http://localhost:1234/OrderHistory/Orders/dropbox1val/dropbox2val/dropbox3val
How to rewriting in asp.net mvc 4?
You need to refine your URL Scheme in the RegisterRoutes(RouteCollection routes)method. I think somethink like the following might give you a clue.
routes.MapRoute("RouteName", "Dropdown1{variableNameHoldingTheValue}/Dropdown2{variableNameHoldingTheValue}/DropDown3{variableNameHoldingTheValue}",
new { controller = "ControllerName", action = "ActionName" },
// You might add consrtaints here
);
EDIT:
if you want this URL to be your default
http://localhost:1234/OrderHistory/Orders (default)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "OrderHistory", action = "Orders", id = UrlParameter.Optional }
);
This is my routing configuration of my mvc3 application
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults:
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
As you can see this is the default routing of a mvc3 application and you can notice that I don't change it at all. So when I was tried to use the url helper RouteUrl like this
#Url.RouteUrl("Default",
new { Action = "RegistrarPago",
IDPago = ViewBag.IDPago,
confirmNumber = ViewBag.ConfirmationNumber },
Request.Url.Scheme)
The output is this
http://localhost/DescuentoDemo/pago/RegistrarPago?IDPago=60&confirmNumber=1798330254
This url it's wrong basically for this characters amp; What's wrong with the helper I'm assuming that's a encoding problem but why?
The # Razor function does HTML encoding by default. There's nothing wrong with the Url.RouteUrl helper. It's the context you are using it in.
It' as if you wrote the following in a Razor view:
#("http://localhost/DescuentoDemo/pago/RegistrarPago?IDPago=60&confirmNumber=1798330254")
You are outputting the result of it on an HTML page, so the correct thing to do is to HTML encode it. If you don't want to HTML encode then use the Html.Raw function:
#Html.Raw(Url.RouteUrl("Default",
new { Action = "RegistrarPago",
IDPago = ViewBag.IDPago,
confirmNumber = ViewBag.ConfirmationNumber },
Request.Url.Scheme))
And if you want to generate for example an anchor pointing to this url you directly use the Html.RouteLink helper in this case.
Recently I've made the transition from Web Forms to MVC 3 and I've been trying to get to grips with MVC routes. I have a somewhat peculiar problem in that when I receive a request to my application (e.g. subdomain1.organisation.com or subdomain2.organisation.com) I wish the default route to be used as follows:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
However, when a request is received by my application through a particular subdomain e.g. subdomain3.organisation.com, I want the application to default to a particular controller. I've been following code at:
http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx
which should what I want. So the code in my Global.asax is as follows:
routes.Add("DomainRoute", new DomainRoute(
"subdomain3.organisation.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Subdomain3Controller", action = "Index", id = "" }
));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When deployed, my application behaves correctly when requests are sent to subdomain3.organisation.com, using Subdomain3Controller. However, when visiting any other subdomain e.g. localhost/Subdomain3Controller/Index my application seems to select the incorrect route.
My form helpers appear to return an incorrect value for:
ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue
#using(Html.BeginForm(ViewContext.Controller.ValueProvider.GetValue("action").AttemptedValue, ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue, FormMethod.Post, new Dictionary<string, object> {{ "id", "formid" } })){
Any ideas why this might be? Any light that anyone could shed on this issue would be much appreciated.
Many thanks in advance.
Have you tried the routing debugger, which is designed to help debug these sorts of problems
Looks like it's installable via Nuget now too.
I've also noticed that if I hard-code the controller name into the BeginForm helper, the incorrect action value is still returned:
using (Html.BeginForm("Index", "Subdomain3Controller", FormMethod.Post, new Dictionary<string, object> { { "id", "formid" } }))
{
generates:
<form id="formid" method="post" action="/">
rather than:
<form id="formid" method="post" action="/Subdomain3Controller">
when viewing:
http://localhost/Subdomain3Controller/ or http://localhost/Subdomain3Controller/Index
Stumbled on a similar problem and managed to find a solution for this problem. I'm aware this might not help the original author, but it might help some other people who end up here via search.
Anyway, it seems the route name "Default" doesn't add much weight. When BeginForm is constructing its URL it takes the first route from the route collection that 'fits'. I didn't dig too deep into how this all works internally.
What I did to solve this problem was add a constraint to the subdomain route so it can only be used for the Subdomain3Controller, as such:
var domainRoute = new DomainRoute(
"subdomain3.organisation.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Subdomain3Controller", action = "Index", id = "" }
);
domainRoute.Constraints = new RouteValueDictionary();
webserviceRoute.Constraints.Add("Controller", "Subdomain3Controller");
routes.Add("DomainRoute", domainRoute);
[edit]
After thinking about this a little bit more and realizing my situation was a bit different from the situation of the original poster. The above won't work, because the controller is not inside of the URL anymore.
A solution might be to switch the order of the routes, and add a NotEqual constraint for the subdomains to the default route. As described in http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx
[/edit]