简体   繁体   English

在 MVC 中使用 JsonResult 重定向到操作

[英]Redirect to action with JsonResult in MVC

I have a Room record in my database and I want to edit it using a JsonResult Edit method in RoomController like this:我有一个房间记录在我的数据库,我想用编辑JsonResult Edit的方法RoomController这样的:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Edit(RoomViewModel roomViewModel)
    {
        if (roomViewModel == null) throw new ArgumentNullException(nameof(roomViewModel));
        try
        {
            var apartmentRoomViewModel = new ApartmentRoomViewModel
            {
                Id = _entities.ApartmentRoom.Where(x => x.RoomID == roomViewModel.Id).Select(x => x.Id).Single(),
                ApartmentID = _entities.ApartmentRoom.Where(x => x.RoomID == roomViewModel.Id).Select(x => x.ApartmentID).Single(),
                RoomID = roomViewModel.Id
            };
            apartmentRoomViewModel.ApartmentID = roomViewModel.SelectedApartmentID;

            var apartmentRoom = AutoMapper.Mapper.Map<ApartmentRoom>(apartmentRoomViewModel);
            _entities.ApartmentRoom.AddOrUpdate(apartmentRoom);
            _entities.SaveChanges();

            var room = AutoMapper.Mapper.Map<Room>(roomViewModel);
            var status = _roomRepository.Update(room);
            _roomRepository.Save();

            return Json(new { status, message = "Success!", url = Url.Action("List", "Room") });
        }
        catch
        {
            return Json(new { status = false, message = "Error!" });
        }
    }

After the method works, edit is successful but I cannot redirect the page to /Room/List.该方法工作后,编辑成功,但我无法将页面重定向到 /Room/List。 Instead, I am encountering a page like this:相反,我遇到了这样的页面:

结果错误

My Script我的脚本

<script type="text/javascript">
$(document).ready(function () {
    $("#RoomEdit").click(function (e) {
        e.preventDefault();
        var data = {
            DoorNumber: $("#DoorNumber").val(),
            FloorNumber: $("#FloorNumber").val(),
            Capacity: $("#Capacity").val(),
            SelectedApartmentID: $("#SelectedApartmentID option:selected").val()
        }
        $.ajax({
            type: "POST",
            url: '@Url.Action("Edit","Room")',
            dataType: "json",
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (result) {
                if (result.status) {

                    window.location.href = result.url;
                }
            },
            error: function () {
            }
        });
        return false;
    });

});

Edit.cshtml编辑.cshtml

<div class="row">

<div class="col-md-10 offset-md-1">
    <div class="box">
        <div class="box-header">
            <h2>@ViewBag.Title</h2>
        </div>
        <div class="box-divider m-a-0"></div>
        <div class="box-body">
            @using (Html.BeginForm("Edit", "Room", FormMethod.Post))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group row">
                    @Html.LabelFor(x => x.DoorNumber, new { @class = "col-sm-2 form-control-label" })
                    <div class="col-sm-10">
                        @Html.TextBoxFor(x => x.DoorNumber, new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.DoorNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(x => x.FloorNumber, new { @class = "col-sm-2 form-control-label" })
                    <div class="col-sm-10">
                        @Html.TextBoxFor(x => x.FloorNumber, new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.FloorNumber, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(x => x.Capacity, new { @class = "col-sm-2 form-control-label" })
                    <div class="col-sm-10">
                        @Html.TextBoxFor(x => x.Capacity, new { @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.Capacity, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group row">
                    @Html.LabelFor(x => x.ApartmentName, new { @class = "col-sm-2 form-control-label" })
                    <div class="col-sm-10">
                        @Html.DropDownListFor(x => x.SelectedApartmentID, Model.ApartmentList, new { @class = "form-control", id = "SelectedApartmentID" })
                    </div>
                </div>
                <div class="form-group row m-t-md">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="button" id="RoomEdit" class="btn green">Düzenle</button>
                    </div>
                </div>
            }
        </div>
    </div>
</div>

I couldn't understand what is wrong with my code.我不明白我的代码有什么问题。 Any help will be appreciated.任何帮助将不胜感激。

Make your Button first with type="Button" instead of Submit, also change the click function id from btnAdd to btnEdit .首先使用type="Button"而不是 Submit 来创建您的 Button,同时将单击函数 ID 从btnAdd更改为btnEdit

At server side, roomViewModel.Id will be getting 0 if you using old method, instead of this do serialize so you can get all the Inputs at server side method.在服务器端,如果您使用旧方法,roomViewModel.Id 将获得 0,而不是这样做序列化,以便您可以在服务器端方法中获取所有输入。

Also use, @Html.HiddenFor(x => x.id) to pass the Id to Method.还可以使用@Html.HiddenFor(x => x.id)将 Id 传递给 Method。

Try this function so you can call your Method with AJAX,试试这个功能,这样你就可以用 AJAX 调用你的方法,

<script type="text/javascript">
    $(document).ready(function () {
        $("#RoomEdit").click(function (e) {
            e.preventDefault();
            var data = $("#formName").serialize();
            $.ajax({
                type: "POST",
                url: '@Url.Action("Edit", "Room")',
                data: data,
                success: function (result) {
                    if (result.status) {
                        alert(result.message);
                        setTimeout(function () {
                            window.location.href = result.url;
                        }, 1000);
                    }
                }
            });
        });
    })
</script>

You have code to do ajax submit.你有代码做ajax提交。 But from the image you shared, it looks like it is doing a normal form submit.但是从你分享的图片来看,它看起来像是在做一个普通的表单提交。 Make sure that you are preventing the default form submit behavior when the button is clicked.确保您在单击按钮时阻止了默认的表单提交行为。

You already have return false;你已经有return false; which should do it.应该这样做。

It should work as long as you do not have other script errors in the page .只要页面中没有其他脚本错误,它就应该可以工作。 (you can verify this by opening up the browser console) (您可以通过打开浏览器控制台来验证这一点)

Also make sure that you are returning true as the value of status property of the json data you are returning.还要确保您返回true作为您返回的 json 数据的 status 属性的值。 There is no need to specify JsonRequestBehavior.AllowGet enum in the Json method overload when you are returning from an HttpPost action method.从 HttpPost 操作方法返回时,无需在 Json 方法重载中指定JsonRequestBehavior.AllowGet枚举。 It is needed if your action method is HttpGet如果您的操作方法是 HttpGet,则需要它

return Json(new { status= true, message = "Success!", url = Url.Action("List", "Room") });

Also, it does not make any sense to have the $.notify call after you redirect to the new page.此外,在重定向到新页面后调用$.notify没有任何意义。 That means that call will not be executed at all!这意味着根本不会执行调用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM