whistleblower whistleblower - 1 year ago 126
Ajax Question

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:

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.

Answer Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download