Reputation: 4231
I need to take GET fields from my asp.net web app (first name and last name). It needs to send that data from frontend(asp.net web app) using JSON to MVC 3 app. MVC 3 App would communicate with database, retrieve values and should serialize them into json object and POST to the front end(ASP.NET web app). Can anyone explain with a sample code how I would accomplish this?
Upvotes: 2
Views: 737
Reputation: 1039268
You could use the WebClient class. It allows you to send HTTP requests to any web application. As far as the JSON part is concerned you will need a JSON serializer. You could use the built-in JavaScriptSerializer class or a third party such as Json.NET.
So let's suppose that you have the following controller action in your ASP.NET MVC 3 application that you want to invoke:
[HttpPost]
public ActionResult Foo(Bar bar)
{
...
return Json(new
{
status = "OK"
});
}
where the Bar
class contains some properties (could be simple or complex types):
public class Bar
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now you could invoke it like this from the client side:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new
{
firstName = "first",
lastName = "last"
});
var resultJson = client.UploadString("http://example.com/foo", json);
var result = serializer.Deserialize<Result>(resultJson);
}
where you would define the Result
class to match the JSON structure returned by the application:
public class Result
{
public string Status { get; set; }
}
Upvotes: 4