views:

82

answers:

2

I'm using ASP.NET MVC (I'm really new to both asp.net and the asp.net mvc type projects, but trying hard to learn).

I've set up MVC with a controller so that it runs a C#.net method which;

  1. queries an mssql db
  2. converts it to json
  3. returns the json string

It's called from the javascript by requesting an url with a parameter. But what I need now is for the C# part to read two integer variables from the javascript. What would be the best way to do that, and does anyone have any good examples/code that I could look at?

It would be extremely helpful. Especially if there are smart ways of doing it with jquery / asp.net (mvc)

+2  A: 

In your controller:

public JsonResult GetPony(string Name, string Color) {
  return Json(new Pony(Name, Color), JsonRequestBehavior.AllowGet);
}

In your javascript:

$.get("/Controller/GetPony", {
  Name: "foo",
  Color: "bar"
});

jQuery will take care of moving stuff from the object into the querystring and MVC will take care of moving stuff from the query string into the call to your action.

svinto
A: 

To do that you need to send it as part of the ajax request. C# can't read your javascript, it can only read the request parameters.

If you're using jQuery, a request might look like this:

$.ajax({
    url:"/products/detail",
    type: "get", (or post, etc)
    dataType: "json",
    data: {productId: 55, culture:"en-US"},
    success: your_success_callback,
    error: function(e) { alert("An error occurred! " + e); }
});

The line that is interesting there is the data setting. It will serialize the data into name=val&name=val and send it to the server. If the type is set to GET then that will be appended to the querystring on the URL. If it's set to POST, then it will be embedded as part of the request.

The server portion doesn't care which. It can retrieve it like this:

public class ProductsController : Controller
{
    public ActionResult Detail(int productId, string culture)
    {
        //your logic here
    }
}
Ben Scheirman