Issue with Url routing - Asp.Net MVC Razor - c#

I use "/Controller/ActionName" url format for my ajax calls. This pattern works fine with my development server that has this pattern
/Controller/ActionName
My application has been deployed to IIS with the following url pattern
/domain/Controller/ActionName
So whenever I call a resource it routes to /Controller/ActionName instead of /domain/Controller/ActionName there by resulting in 404 error. Is there any quick fix for this by modifying the routeconfiguration such that it works on both the devl as well as the IIS.

If you defining the relative urls "manually" as a string try not using a '/' in the beginning.
"Controller/ActionName"
Edit
What I've done the the past is included a Partial Razor View that is responsible of setting urls using #Url.Action()
Partial - Shared/JavascriptUrlsPartial.cshtml
<script type="text/javascript">
(function ($, app) {
app.urls =
{
actionA: '#Url.Action("Controller", "ActionA")',
};
})(jQuery, app = app || {});
</script>
Then you reference the rendered url in javascript.
$.ajax({
url: app.urls.actionA,
//etc
})
This partial is then included in the _Layout.cshtml.

In my Razor view, we have Ajax calls like:
var model = { searchId: searchId, newSearchName: searchName, newSearchDescription: description };
$.ajax({
url: '#Url.Action("Rename", "Search")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
We have not done anything special in local or production environment. We host the application on IIS 7.5.
I could not make out what's different in your case from your question and comments. If this does not solve the problem please add more information around your setup.

Related

how to call url in ajax json request

i need to call webservice from a directory in my project but
url: "~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch" but it is not working
$.ajax({
url: "~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch",
data: "{ 'ranumber': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
})
hiow can i call the url from a directory
Try building up the url with the abolute server path, e.g. using window.location like this:
$.ajax({
url: window.location.host + "/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch"
...
A relastive url should also work. Just leave out the "~"-prefix. Note that you should execute JavaScript code not locally but from a real http server. Debugging in Visual Studio uses a local http server, so this will do.
Urls starting with ~/ are ASP.NET Urls. To use it in JavaScript you need to map it to actual Urls. Render the path on your page into a JavaScript variable and then use it in your script.
HttpContext.Current.Server.MapPath("~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch") will get you the actual path. I have not used ASP.NET in a while, so I do not remember the correct asp:label syntax anymore to get you the full way.

Call method in code-behind (secure page) from client (JavaScript)

Let me start of by saying I am very new to ASP.NET and C#.
I have a simple web form containing data which I want to send to a code-behind page.
The idea is to capture the data and send it as a JSON object to a code-behind method.
Note that this is done via JavaScript/AJAX (see code below).
The code-behind method will then do a trivial HTTP "PUT" request to update the data.
The .apsx page is located in the Secure folder (uses a Secure Master).
Don't know if that will affect the method calling?
Following is the code I have thus far.
JavaScript/AJAX:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "PUT",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
Code-behind:
namespace PartyAtVendors.Secure
{
[WebService]
public partial class Profile : System.Web.UI.Page
{
[WebMethod]
public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
{
return true;
}
}
}
Update:
Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:
PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)
Such static methods are called Page Methods in asp.net.
You call them form javascript like this on the same page as follows:
string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);
You need to have a ScriptManager on the page and it should have PageMethods enabled
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
The page method must be defined on the page. It cannot be defined in a control, master page, or base page.
PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie. Using the PUT verb is causing the 404 error.
ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used
when invoking web methods using JSON
Your webmethod & javascript method should be on same page.
Hi managed to sort out what was wrong.
I simply changed the HTTP method to "POST" as follows:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "POST",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
$.ajax(saveOptions);
This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

Is this possible through javascript?

I am currently working on asp.net project. I use oodle web service. Oodle provides result via URL. I use Link to get data from the URL.
From code behind I use following code to fetch the resultant string :
string url =
#"http://api.oodle.com/api/v2/listings?
key=TEST&region=chicago&category=vehicle&format=json";
var jsonString = new WebClient().DownloadString(url);
Now , My problem is I use button click event to run that code. But is this through JavaScript ? Because If I use Javascript it will be easier to access my resultant data.
It looks like this API returns JSONP which means that you could consume it directly from javascript. For example if you use jQuery you could use the $.ajax() method:
$.ajax({
url: 'http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonOodleApi',
success: function(result) {
alert(result.current.region.id);
}
});
Here's a live demo.
And if you don't use jQuery you could simply define a callback:
var jsonOodleApi = function(result) {
alert(result.current.region.id);
};
and then include a <script> pointing to this url:
<script type="text/javascript" src="http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json"></script>
Here's a live demo.
Obviously you could inject this script tag dynamically into the DOM whenever you want to invoke the API call.
You can make Ajax requests to the page through Javascrypt.
here's a tutorial on that
If you are using some JavaScript frameworks, like JQuery, those requests would be easier to make, as the AJAX requests are kinda not cross-browser compatible.
the JQuery version
What you want is an AJAX request. It it certainly possibly to do without libraries, but due to crossbrowser issues I would recommend using a library. With jQuery for example it could look like this (in a document ready part of script):
$("#idOfButton").click(function() {
$.get('string url= #"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json', function(jsonString) {
alert('Data is now in variable jsonString!');
});
});

using wcf instead of web service !

I'm using ajax in my website to call some information from a UserControl called NewsFeed.ascx which is found in the folder 'controls', my way is to make a web service page (in a folder called WebMethods) which contain a function in my case called GetRSSReader which returns a string format:
[WebMethod]
public string GetRSSReader()
{
Page page = new Page();
UserControl ctl =
(UserControl)page.LoadControl("~/Controls/NewsFeed.ascx");
page.Controls.Add(ctl);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
then I call this page using Jquery (which I found it too heavy) to get the returned data as a JSON like this :
<div id="Content"></div>
<script type="text/javascript" defer="defer" src="../JAVA/Default.js"></script>
>
$(document).ready(Update);
function Requests()
{
$.ajax({
type: "POST",
url: "../WebMethods/Feed.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#Content').html(msg.d);
}
});
}
the Jquery.js and this page (default.js) founded in the folder Java
my question : can I not to use webService and instead using WCF !!! and how !?
What you refer to as "web services" is the old "ASMX Web Service" feature of .NET (sometimes known as ASP.NET Web Services).
WCF is the replacement for ASMX web services.
See https://stackoverflow.com/tags/wcf/info for some getting-started information.
If you're just returning JSON then I highly recommend you simply use an HttpHandler instead of some combination of WCF, SOAP, UserControls, and whatever else you're throwing in there. Here's a quick tutorial on the subject. You'd save yourself the overhead of page life-cycle stuff that you don't need. And returning the JSON is as simple as serializing your return values with the JavaScriptSerializer.

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories