Reputation: 707
I have inherited a web app and I need to convert a client side ajax post into server side asp.net code ( C#). I am not sure what the best approach is to accomplish this, I am pretty new to ajax posts but this code seems to be posting info to a page in the same project so I am assuming there is a much easier way to accomplish this server side just wanted to have someone confirm that I am not crazy...
$.ajax({
// type: "POST",
// url: '<%= ResolveUrl("~/default.aspx") %>/Login',
// data: parameters,
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function (msg) {
// if (msg.d == "success") {
// $.modal.autoResize = false;
// ResizeModal();
// var redirectUrl = $('#<%= btnSubmit.ClientID %>').attr('data-redirecturl');
// if (redirectUrl != null && redirectUrl.length > 0) {
// window.location = redirectUrl;
// }
Upvotes: 3
Views: 8584
Reputation: 6270
You can use an HttpWebRequest
. It'll be something like this:
var httpWebRequest = (HttpWebRequest)WebRequest.Create( ResolveUrl("~/default.aspx"));
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
string json = .... //Constrtuct your json here
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var response = httpWebRequest.GetResponse();
Upvotes: 6
Reputation: 5903
Ajax call is just a special case of HTTP request, there is no specific way out of the box in .net, so your question is about how to make HTTP request in .net and there are multiple ways:
Making and receiving an HTTP request in C# or using WebApi, which is the easiest way IMO.
and I would recommend to use Chrome Dev tools to capture exact HTTP request and then Fiddler to do the same for the server side and compare them to make sure they are similar.
BUT it looks like you need something slightly different, looks like your page just posting data to default page and then redirects to that page, that could be done by a simple form submit
Upvotes: 7
Reputation: 4104
This has gotten much easier with WebAPI on the server side (ASP.Net MVC4 Controller if you want to host under IIS; WebAPI self hosted under a separate, standalone app is also possible) and HttpClient on the client side.
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
Upvotes: 5