从View到Action发送数据

时间:2019-03-04 13:40:24

标签: javascript asp.net-mvc

如何将视图中的一些数据发送回控制器?

这是我从中获取数据的选择(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>

这是我尝试用于发送回数据的脚本:

<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() }
    })
}

最后是控制器:

    [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();
    }

1 个答案:

答案 0 :(得分:2)

首先,您必须在选择中添加 option值

 <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>

然后将您的loadJasonData()方法更改为此

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

最后一次删除您的操作中的[HttpGet]

  [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();
    }

注意:您的操作会返回视图。如果要返回 json结果,则必须使用return Json(yourData);