Tuesday 29 July 2014

How to Post JSON Data to an MVC5 Controller via Ajax

It's just a simple form where you enter your first name and last name, and then use a multiselect dropdown to pick your favorite bands.

Home













and enter your First name, Last name and select your favorite Car.














Step 1: First Create PersonController.css

 [HttpGet]
        public ActionResult Index()
        {
            return View(new PersonModel());
        }

        [HttpPost]
        public JsonResult BadSave(string first, string last, List<string> favoriteBands)
        {
            Console.WriteLine(first);
            Console.WriteLine(last);
            Console.WriteLine(String.Join(" ",favoriteBands));

            return Json(new { result = "saved the bad way" });
        }

        [HttpPost]
        public JsonResult GoodSave(PersonModel model)
        {
            Console.WriteLine(model.First);
            Console.WriteLine(model.Last);
            Console.WriteLine(String.Join(" ", model.FavoriteBands));

            return Json(new { result = "saved the good way" });

        }


Step 2 : Create PersonModel.css Model

public class PersonModel
    {
        [DisplayName("First Name")]
        public string First { get; set; }

        [DisplayName("Last Name ")]
        public string Last { get; set; }

        [DisplayName("Favorite Car")]
        public List<string> FavoriteBands { get; set; }
    }

Step 3 : Create the View ie Index.cshtml

@model MVCJsonPost.Models.PersonModel
@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Home</h2>

<div>
    @Html.LabelFor(m => m.First)
    @Html.EditorFor(m => m.First)
</div>

<div>
    @Html.LabelFor(m => m.Last)
    @Html.EditorFor(m => m.Last)
</div>

<div>
    @Html.LabelFor(m => m.FavoriteBands)
    @Html.DropDownListFor(m => m.FavoriteBands, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Honda City"  },
                       new { value = 1 , text = "Renault fluence" },
                       new { value = 2 , text = "Hyundai xcent"}
                    },
                  "value",
                  "text",
                   Model.FavoriteBands),
                    new { multiple = "multiple" })


</div>

<div>
    <input type="button" value="Bad Submit" id="bad" />
    <input type="button" value="Good Submit" id="good" />
</div>

<label id="result"></label>

Step 4: Create the js file i.e person.js in Script Folder

$(document).ready(function () {
    $('#good').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/GoodSave",
            dataType: 'json',
            contentType: "application/json",
            type: "POST",
            data: JSON.stringify(request), //Ahhh, much better
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });

    $('#bad').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/BadSave",
            dataType: 'json',
            type: "POST",
            data: "first=" + request.First + "&last=" + request.Last + "&favoriteBands=" + request.FavoriteBands, //How do you encode an array?? This doesn't even work right
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });
});

function PersonModel() {
    var self = this;
    self.First = $("#First").val();
    self.Last = $("#Last").val();

    self.FavoriteBands = $.map($('#FavoriteBands option:selected'),
                      function (e) { return $(e).val(); });
}


Run The Application  and fill the form and place some breakpoint to test and debug line by line















Done :)




0 comments:

Post a Comment