5

I am new to ASP.NET MVC and learning. So far I have figured out how I can create a JSON Object and return that as a response to a request. However, I'm not able to pass a JSON body as part of a POST request like I normally did using Java.

Here is the code how I did this there -

@Path("/storeMovement")
@POST
@Consumes("application/json")
@Produces("application/json")
public String storeTrace(String json) {
  JSONObject response = new JSONObject();
  JSONParser parser = new JSONParser();
  String ret = "";

  try {
      Object obj = parser.parse(json);
      JSONObject jsonObj = (JSONObject) obj;

      RecordMovement re = new RecordMovement((double) jsonObj.get("longitude"), (double) jsonObj.get("latitude"), (long) jsonObj.get("IMSI"));
      ret = re.Store();

      // Clear object
      re = null;
      System.gc();

      response.put("status", ret);
  } catch (Exception e) {
      response.put("status", "fail " + e.toString());
  }
  return response.toJSONString();
}

I tried the same in the ASP.NET Action method but the value in the string parameter a is null as seen while debugging. Here's the code for the Action method -

public string Search(string a)
{
    JObject x = new JObject();

    x.Add("Name", a);

    return x.ToString();
}

It works fine when I use an Object (for example - Book) like so -

public string Search(Book a)
{
    JObject x = new JObject();

    x.Add("Name", a.Name);

    return x.ToString();
}

In that case, the book's name gets de-serialized just fine as I would expect. The class definition for the Book class -

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Can somebody please advise what I'm doing wrong? Is there no way to take in a string and then de-serialize? I'd like to be able to take in JSON without having to use an Object

4
  • how do you call the controller method? can you post the post request part? Commented Aug 16, 2015 at 12:39
  • try using method paratemer with (string Name) Commented Aug 16, 2015 at 12:46
  • @vinayan I do the post request using the POSTMAN add-on for Chrome right now. I add a header indicating content-type as application/json. The request type is set to POST and has a JSON body - { "Name": "Normally", "ID": 55 } Commented Aug 16, 2015 at 13:04
  • @AjayKelkar check if my answer is of any help Commented Aug 16, 2015 at 14:23

3 Answers 3

6

As for as understand you want pass entire of request body to a string without any binding so you could handle passed string data with your desired way.

To aim this purpose simply write your own model binder:

public class RawBodyBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if(typeof(string)!=bindingContext.ModelType)
             return null;

        using (var s = new StreamReader(controllerContext.HttpContext.Request.InputStream))
        {
            s.BaseStream.Position = 0;
            return s.ReadToEnd();
        }      
    }
}

And in you action method assign your binder to desired parameter:

public string MyAction([ModelBinder(typeof(RawBodyBinder))]string json)
{
}

But MVC has own JSON model binder as well if your data is a standard JSON and in request body with Content-Type: application/json header you could use MVC's JSON model binder to activate JSON model binder simply add following line in Global.asax.cs file:

protected void Application_Start()
{
    // some code here

    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
Sign up to request clarification or add additional context in comments.

Comments

5

The first thing in asp.net mvc to post a data is to decorate the method with this attribute [Httpost] it's mean passing a string should look like

[HttpPost]
public string Search(string a){
    // your code
}

The default value is [HttpGet] that get parameters from url. For Post request you need to.

Edit:

And look the answer from vinayan

with jquery:

$.ajax({
  method: "POST",
  url: "Home/Search",
  data: {'a': 'yourstring'}
})

1 Comment

Thanks! Added the annotation but that still didn't work. Parameter a was still showing a null value. So in addition to that, I added what @vinayan said about having the key name in the JSON match the parameter name and it works now. So I take away two key lessons from this question :)
1

The name of the parameter you send is used for the de-serialization. So in in this case, "a" should be part of json.

public string Search(string a)

so you will have to use,

$.ajax({
  method: "POST",
  url: "Home/Search",
  data: {'a': 'yourstring'}
})

1 Comment

Thanks! I did this in addition to adding the [HttpPost] annotation to the method and it worked then

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.