简体   繁体   中英

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:

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

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

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.

Also use, @Html.HiddenFor(x => x.id) to pass the Id to Method.

Try this function so you can call your Method with 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. 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; 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. There is no need to specify JsonRequestBehavior.AllowGet enum in the Json method overload when you are returning from an HttpPost action method. It is needed if your action method is 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. That means that call will not be executed at all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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