.netmodel-view-controllerajax.beginform

asp.net mvc5 JsonResult usage


I was working on a project and I wondered how to handle json result as an object. I succeed using a partial view as a result but I just wonder that Is that possible if I return a json result as a List.

My expected result is like that:

 @using (Ajax.BeginForm("AddMission", "Mission", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "ajaxEtki", InsertionMode = InsertionMode.InsertAfter }   new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }){
// Do some staff
}

And In the controller part

public JsonResult ()
{
     List<Missions> missions = _db.Missions.ToList();
     return Json(missions,JsonBehavior.AllowGet);
}

I just wonder how to handle the result in View Part(I want to use the result like objects.)

// The part I wonder is usage of that script part. //Because I didnot succeed in that script part. Can someone help me about how to convert that jsonresult to object list?

<script type="text/javascript">
        function OnSuccess(response) {
            var obj = response.get
            alert(response);
            var isss = JSON.parse(response);

                var target = $("#ajaxEtki");
                target.empty();
                for (var i = 0; i < response.length; i++) {
                    var product = response[i];
                    alert(product);
                    target.append(product.GOREVTURADI + "<br />");
                }
            }
            function OnFailure(response) {
                alert("false")
            }
        </script>

Thank you in advance for your help.

Regards.


Solution

  • Here's a quick sample.

    1. Add unobtrusive-Ajax to you project using command Install-Package Microsoft.jQuery.Unobtrusive.Ajax in Package Manager Console.

    2. Example codes as below:

    Model

    public class Mission
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Controller

        private readonly List<Mission> _missions = new List<Mission>()
        {
            new Mission(){Name = "qw",Id = 1},
            new Mission(){Name = "er",Id = 2},
            new Mission(){Name = "ty",Id = 3}
        };
        public ActionResult Mission()
        {
            return Json(_missions, JsonRequestBehavior.AllowGet);
        }
    

    View

        </div>
        @using (Ajax.BeginForm("Mission", new AjaxOptions() { OnSuccess = "submitMissionSuccess" }))
        {
            <input type="submit" value="Ok"/>
        }
    

    Scripts in view

    @section scripts
    {
        <script>
            function submitMissionSuccess(response) {
                for (var i = 0; i < response.length; i++) {
                    $('#jsonTarget').append("<p>" + response[i].Name + "</p>");
                }
            }
        </script>
    }