There is a representation of the following type, which needs to be remade under 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 ModelC controller. It has a ViewM method with a return value of type 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); } 

Well, a class with properties

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

If the ViewM were of type ActionResult, then in any field it would be easy to pass the Name value. 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 in the same way you can not do 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 the values ​​are not transferred from Ajax.BeginForm ... How do I fix Ajax.BeginForm so that the values ​​are successfully passed to Json?

    1 answer 1

    The Ajax.BeginForm method has an overloaded version, one of the parameters of which is object routeValues ​​or RouteValueDictionary routeValues. So, with this parameter you can transfer the values ​​included in the action method as (for object):

      new {str = "first parameter value", str2 = "second parameter value"}, 

    for RouteValueDictionary:

      new RouteValueDictionary{{"str","first parameter value"}, {"str2","second parameter value"}}. 

    The important point is the names of the incoming parameters of your method and the names of the parameters for routeValues ​​- they must match. Therefore, I did not change their names in the above example, but made a match with the names of your ViewM method.