5

I've seen how I can serialize to an object in JSON. How can I POST a string which returns a ViewResult?

            $.ajax({
                url: url,
                dataType: 'html',
                data: $(this).val(), //$(this) is an html textarea
                type: 'POST',
                success: function (data) {
                    $("#report").html(data);
                },
                error: function (data) {
                    $("#report").html('An Error occured.  Invalid characters include \'<\'. Error: ' + data);
                }
            });

MVC

   [HttpPost]
    public ActionResult SomeReport(string input)
    {
        var model = new ReportBL();
        var report = model.Process(input);
        return View(report);
    }
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • Have a look at this post and Darin's answer: http://stackoverflow.com/questions/5046930/jquery-send-string-as-post-parameters – Sam Aug 26 '12 at 18:02

4 Answers4

5

How about:

        $.ajax({
            url: url,
            dataType: 'html',
            data: {input: $(this).val()}, //$(this) is an html textarea
            type: 'POST',
            success: function (data) {
                $("#report").html(data);
            },
            error: function (data) {
                $("#report").html('An Error occured.  Invalid characters include \'<\'. Error: ' + data);
            }
        });

If you make the data a JSON object with a key that matches the parameter name MVC should pick it up.

On the MVC side...

[HttpPost] 
public ActionResult SomeReport() 
{ 
    string input = Request["input"];
    var model = new ReportBL(); 
    var report = model.Process(input); 
    return View(report); 
} 
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
Davy8
  • 30,868
  • 25
  • 115
  • 173
  • I combined this with one of Darin's answers and it works really well. http://stackoverflow.com/questions/5088450/simple-mvc3-question-how-to-retreive-form-values-from-httppost-dictionary-or – P.Brian.Mackey Aug 26 '12 at 18:07
0

You might want to return your result as a json format. Not sure how to exactly do this with asp.net, but if it were Rails, it would be return @foo.to_json

Christian Fazzini
  • 19,613
  • 21
  • 110
  • 215
0

You need to add a contentType. Look at the jQuery API:

http://api.jquery.com/jQuery.ajax/

Sam
  • 15,336
  • 25
  • 85
  • 148
0

You could use [FromBody] attribute in your action method, it specifies that a parameter or property should be bound using the request body.

[HttpPost]
public ActionResult SomeReport([FromBody] string input)
{
    var model = new ReportBL();
    var report = model.Process(input);
    return View(report);
}
Oscar Acevedo
  • 1,144
  • 1
  • 12
  • 19