在从控制器接收到视图的json响应后重定向到另一个页面在ASP.NET Core MVC中不起作用

yvfmudvl  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(155)

我一直在尝试在ASP.NET Core MVC中创建一个编辑密码的功能,从视图向控制器发送请求的功能工作正常,我的问题是当控制器向视图返回JSON时,结果是JSON响应打印在屏幕上,而不是将页面重定向到索引,如果响应成功。
你能提供一个答案或参考,可以帮助我吗?
我尝试发送json(Response)json(new {success = true};
控制器代码为:

// GET
public async Task<IActionResult> EditPassword(int? id)
{
    if(id == null || _context.NameEmailTables == null)
    {
        return NotFound();
    }

    var nameEmailTable = await _context.NameEmailTables.FindAsync(id);

    if (nameEmailTable == null)
    {
        return NotFound();
    }

    var model = new EditPassword();

    return View(model);
}

[HttpPost]
public async Task<IActionResult> EditPassword(EditPassword formData)
{
    try
    {
        var UserId = 1;
        var user = await _context.NameEmailTables.FindAsync(UserId);

        if (ModelState.IsValid)
        {
            if (user != null && user.Password == formData.OldPassword)
            {
                user.Password = formData.NewPassword;
                _context.Update(user);
                await _context.SaveChangesAsync();

                return Json(new { success = true });
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Old password is incorrect");
            }
        }

        return Json(new {success = false});
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine("Error in EditPassword action: " + ex.Message);
        return Json(new { success = false });
    }
}

字符串
视图标记和代码是:

@model EditEmail.Models.EditPassword

@{
    ViewData["Title"] = "EditPassword";
}

<h1>EditPassword</h1>

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="EditPassword" id="form">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="UserId" />
            
            <div class="form-group">
                <label asp-for="OldPassword" class="control-label"></label>
                <input asp-for="OldPassword" class="form-control" />
                <span asp-validation-for="OldPassword" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <label asp-for="NewPassword" class="control-label"></label>
                <input asp-for="NewPassword" class="form-control" />
                <span asp-validation-for="NewPassword" class="text-danger"></span>
                <span id="NewPasswordError" asp-validation-for="NewPassword" class="text-danger"></span>
            </div>
            <br/>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const btn = document.querySelector(".btn");
        const form = document.querySelector("#form");
        btn.addEventListener("click", function (e) {
            e.preventDefault();
            let formData = {};
            let formElements = form.elements;
            for (let i = 0; i < formElements.length; i++) {
                let element = formElements[i];
                if (element.name) {
                    formData[element.name] = element.value;
                }
            }
         
            fetch("\\NameEmailTables/EditPassword", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            }).then(async response => 
                {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const res = await response.json();
                if (res.success) {
                    window.location.href = "/NameEmailTables/";
                } else {
                    NewPasswordError.textContent = "The Old Password is wrong";
                
                }).catch(error => console.error("An error occurred:", error)
            );

        })
    }
</script>


我也试过:

fetch("\\NameEmailTables/EditPassword", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            }).then(response => 
                {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return await response.json();}).then(data =>
                if (data.success) {
                    window.location.href = "/NameEmailTables/";
                } else {
                    NewPasswordError.textContent = "The Old Password is wrong";
                
                }).catch(error => console.error("An error occurred:", error)
            );

        })


网络和控制台中没有显示错误,但控制器的方向不起作用

bfnvny8b

bfnvny8b1#

如果你想让一个mvc控制器(没有[ApiController]属性)接收json值,你必须添加[FromBody]属性

[HttpPost]
public async Task<IActionResult> EditPassword([FromBody]EditPassword formData)
{
}

字符串
在您的情况下,它将始终返回Json(new {success = false});
网络和控制台中没有显示错误,但控制器的方向不起作用

return Json(new { success = false });


我会返回一个有200个状态代码的ObjectResult,不会在代码中触发catch方法
尝试返回objectresult而不使用200 statue代码,例如:

return BadRequest(new {success=false});

相关问题