1

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:

Wrong result

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.

Utku
  • 301
  • 2
  • 6
  • 18
  • Check the button RoomAdd is with type Button or not?, your code of AJAX looks simple as submit, If you want to show the message then you should use alert first and then redirect aftersometime. – Smit Patel Oct 02 '17 at 16:18
  • @SmitPatel RoomAdd should be RoomEdit. Thanks for the detail I have changed it and edit my question with new changes. RoomEdit's type is submit. I have changed it as type="button" but it didn't even work. – Utku Oct 02 '17 at 16:45
  • @SmitPatel I am quite new in programming. I understood the problem you pointed out but I don't know the exact solution of it. My button is "". – Utku Oct 02 '17 at 16:51
  • Can i see your HTML in question? – Smit Patel Oct 02 '17 at 16:52
  • @SmitPatel I have edited my question and added HTML code. – Utku Oct 02 '17 at 16:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155778/discussion-between-smit-patel-and-whistleblower). – Smit Patel Oct 02 '17 at 17:06

2 Answers2

1

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>
Smit Patel
  • 2,508
  • 1
  • 18
  • 41
0

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!

Shyju
  • 197,032
  • 96
  • 389
  • 477