将数据从View发送到Action

问题描述 投票:0回答:1

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

这是我从中获取数据的选择(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();
    }
javascript asp.net-mvc
1个回答
2
投票

首先,您必须为选择添加选项值:

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

© www.soinside.com 2019 - 2024. All rights reserved.