使用ajax向控制器发送请求

问题描述 投票:0回答:1

我正在开发 ASP.NET Core MVC 应用程序,我有一个注册页面,如下所示,我想在模型状态为 false 时返回带有错误的视图:

@model WebApplication2PROP.Entities.UserRegister
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<section id="RegSection">
    <div class="container">
        <div class="row justify-content-center align-items-center">
            <div class="col-lg-6 col-md-6 col-sm-12 justify-content-center text-start ">


                    <span asp-validation-for="FirstName" class="Validation"></span>
                    <br />
                    <label for="FirstName" class="form-label">First Name</label>
                    <input type="text" id="FirstName" class="form-control" value="@Model.FirstName" name="FirstName" />
                    <br />

                    <span asp-validation-for="LastName" class="Validation"></span>
                    <br />
                    <label for="LastName" class="form-label">Last Name</label>
                    <input type="text" id="LastName" class="form-control" value="@Model.LastName" name="LastName"/>

                    <br />

                    <span asp-validation-for="UserName" class="Validation"></span>
                    <br />
                    <label for="UserName" class="form-label">User name</label>
                    <input type="text" id="UserName" class="form-control" value="@Model.UserName" name="UserName" />

                    <br />
                    <span asp-validation-for="Phonenumber" class="Validation"></span>
                    <br />
                    <label for="PhoneNumber" class="form-label">PhoneNumber</label>
                    <input type="text" id="PhoneNumber" class="form-control" value="@Model.Phonenumber" name="Phonenumber"/>

                    <br />
                    <span asp-validation-for="Password" class="Validation"></span>
                    <br />
                    <label for="Password" class="form-label">Password</label>
                    <input type="password" id="Password" class="form-control" value="@Model.Password" name="Password" />

                    <br />
                    <span asp-validation-for="ConfirmPassword" class="Validation"></span>
                     <br />
                    <label for="ConfirmPassword" class="form-label">Confirm Password</label>
                    <input type="password" id="ConfirmPassword" class="form-control" value="@Model.ConfirmPassword" name="ConfirmPassword" />


                    <div class="text-center"> <button class="btn text-center RegBut" id="RegBut">Register</button></div>
                    <div class="text-center">
                        Already have an account? @Html.ActionLink("Login","LoginPage","Home",null,new {@class ="btn RegBut"})
                    </div>


                
                 
            </div>
            
        </div>
    </div>
</section>

控制器:

[HttpPost]
        public async Task <IActionResult>  SubmitLogin([FromBody]LogIn user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { data = false });
                }
                else
                {
                    return Ok(new { data = true });
                }
                await operations.Login(user);
                return RedirectToAction("MainPage","Home");
            }
            catch (Exception ex) 
            {
                ModelState.AddModelError(nameof(user.UserName), ex.Message);
                return View("HomePage", user);
            }
        }

现在,我想使用ajax发送数据:

 $("#RegBut").click(function () {
         //   alert("clicked")
            var FirstName=$("#FirstName").val();
            var LastName = $("#LastName").val();
            var UserName = $("#UserName").val();
            var PhoneNumber = $("#PhoneNumber").val();
            var Password = $("#Password").val();
            var ConfirmPassword = $("#ConfirmPassword").val();
            var Data = { FirstName: FirstName, LastName: LastName, UserName: UserName, PhoneNumber: PhoneNumber, Password: Password, ConfirmPassword: ConfirmPassword }
            $.ajax({
                type: "POST",
                url: "/Home/SubmitRegister",
                contentType: "application/json",
                data: JSON.stringify(Data),
                success:function(data)
                {
                    if (data.success)
                    {
                     // Registration was successful, redirect to MainPage
                      window.location.href = '/Home/MainPage';
                     }
                 else 
                 {
                     // Registration failed, update UI with validation errors
                     alert("Data is not success");
                     console.log(data)
                  }
                 },
                error: function (data) 
                {
                    console.log(data);
                }

            });
        });

** 问题是,当用户向控制器提交数据时,如果 ModelState 为 false,如何重定向到上面的视图并使每个验证错误都在相关输入字段上方?**

我尝试返回视图如下:

[HttpPost]
        public async Task <IActionResult> SubmitLogin([FromBody]LogIn user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View("Register",user);
                }
                else
                {
                    return Ok(new { data = true });
                }
                await operations.Login(user);
                return RedirectToAction("MainPage","Home");
            }
            catch (Exception ex) 
            {
                ModelState.AddModelError(nameof(user.UserName), ex.Message);
                return View("HomePage", user);
            }
        }

但它不起作用,它会将 HTML 返回给 ajax。

javascript jquery ajax asp.net-mvc asp.net-core
1个回答
0
投票

这里的问题是您正在使用 jQuery Ajax 来调用控制器方法。这里的问题是,每当发生任何验证错误时,您都会发送完整视图,以便它在响应中呈现整个 HTML。请记住,您正在使用 jQuery Ajax,因此您应该返回如下所示的错误请求,而不是返回视图

if (!ModelState.IsValid)
{
   return BadRequest(ModelState);
}

现在您将收到所有验证消息,并且您可以以相同的方式执行此操作,但此处有例外。

        catch (Exception ex) 
        {
            ModelState.AddModelError(nameof(user.UserName), ex.Message);
            return BadRequest(ModelState);
        }
© www.soinside.com 2019 - 2024. All rights reserved.