locked
Transfer data from the presentation controller with a method JsonResult RRS feed

  • Question

  • User-16611417 posted

    There is a view the following type that you want to convert a json:

    @using (Ajax.BeginForm(new AjaxOptions { Url = Url.Action("ViewM", "ModelC") }))
    {
    <input type="text" name="str" />
    <input type="text" name="str2" />
    <input class="btn" type="submit" value="Отобразить результат" />
    }



    And the controller ModelS. ViewM method to return a Json

    public JsonResult ViewM()
    {
    var result = new List<P>();
    result.Add(new P { Name = "N1", Value = 6 });
    result.Add(new P{ Name = "N2", Value = 6 });
    result.Add(new P{ Name = "N3", Value = 6 });
    result.Add(new P { Name = "N4", Value = 4 });
    return Json(new { Countries = result }, JsonRequestBehavior.AllowGet);
    }



    the properties of the class

    public class P
    {
    public string Name { get; set; }
    public int Value { get; set; }
    }



    If ViewM would type ActionResult, in any field it would have been easy to convey the value of Name. It would look something like this:

    public ActionResult ViewM(string str, string str2)
    {
    var result = new List<P>();
    result.Add(new P { Name = str, Value = 6 });
    result.Add(new P{ Name = str2, Value = 6 });
    result.Add(new P{ Name = "N3", Value = 6 });
    result.Add(new P { Name = "N4", Value = 4 });
    return PartialView(result)
    }



    But the problem is that the same can be done with JsonResult.

    public JsonResult ViewM(string str, string str2)
    {
    var result = new List<P>();
    result.Add(new P { Name = str, Value = 6 });
    result.Add(new P{ Name = str2, Value = 6 });
    result.Add(new P{ Name = "N3", Value = 6 });
    result.Add(new P { Name = "N4", Value = 4 });
    return Json(new { Countries = result }, JsonRequestBehavior.AllowGet);
    }

    Because of Ajax.BeginForm not transmitted values ... How can I fix Ajax.BeginForm, to values successfully transferred to Json?

    Friday, March 4, 2016 8:05 PM

Answers

  • User61956409 posted

    Hi Gadman,

    You could try to use the jQuery Ajax to post the fields value to JsonResult ViewM(string str, string str2).

    $.ajax({
        type: "POST",
        url: '/ControllerName/ViewM',
        data: "{'str':'" + $("input[name='str']").val() + "," + "'str2':'" + $("input[name='str2']").val() + "'}",
        //other options
    
    });
    

    Besides, you could refer to this article.

    http://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 7, 2016 7:58 AM