Cristi Priciu
Cristi Priciu

Reputation: 59

Sending data from View to Action

How do I send some data from the view back to the controller?

This is the select from where I get the data (sel1):

 <div class="form-group" style="margin: 0 auto;">
            <label for="sel1">Select a cat breed:</label>
            <select class="form-control" id="sel1">
                @foreach (var item in Model)
                {
                    <option>
                        @Html.DisplayFor(modelItem => item.BreedName)
                    </option>
                }
            </select>
        </div>

This is the script I tried to use to send data back:

<script>
$(document).ready(function () {
    loadJasonData();
    $("#sel1").change(function () {
        loadJasonData();
    });
});

function loadJasonData() {
    $.ajax({
        type: "POST",
        url: "CatDetails",
        //url: "/CatCompare/CatDetails", i also tried this of url
        cache: false,
        dataType: "json",
         data: { name: $("#sel1").val() }
    })
}

And finally the controller:

    [HttpPost]
    [HttpGet]
    public ActionResult CatDetails(string name)
    {
        var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);

        ViewBag.name = breedName.BreedName;
        ViewBag.lifeSpan = breedName.Lifespan;
        ViewBag.height = breedName.Height;
        ViewBag.weight = breedName.Weight;
        ViewBag.shortDescription = breedName.ShortDescription;
        return View();
    }

Upvotes: 0

Views: 88

Answers (1)

Fatikhan Gasimov
Fatikhan Gasimov

Reputation: 943

First of all you have to add option value to your select:

 <div class="form-group" style="margin: 0 auto;">
            <label for="sel1">Select a cat breed:</label>
            <select class="form-control" id="sel1">
                @foreach (var item in Model)
                {
                    <option value='@item.BreedName'>
                        @Html.DisplayFor(modelItem => item.BreedName)
                    </option>
                }
            </select>
        </div>

Then change your loadJasonData() method to this

function loadJasonData() {
    $.ajax({
        type: "POST",           
        url: "/CatCompare/CatDetails",
        cache: false,
        dataType: "json",
         data: { name: $("#sel1 option:selected").val() }
    })
}

at the last remove [HttpGet] in your action

  [HttpPost]

  public ActionResult CatDetails(string name)
    {
        var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);

        ViewBag.name = breedName.BreedName;
        ViewBag.lifeSpan = breedName.Lifespan;
        ViewBag.height = breedName.Height;
        ViewBag.weight = breedName.Weight;
        ViewBag.shortDescription = breedName.ShortDescription;
        return View();
    }

Note: Your action returns a view. If you want to return json result you have to use return Json(yourData);

Upvotes: 2

Related Questions