简体   繁体   English

如何使用Ajax调用此后操作方法?

[英]How to call this post action method using Ajax?

I am trying to create a form that does an Ajax post for a creation of a new user. 我正在尝试创建一个表单,该表单执行Ajax发布以创建新用户。 My goal is to show a popup indicating the result of the action. 我的目标是显示一个指示操作结果的弹出窗口。 The current version of the action method adds errors to the ModelState if something's wrong, and redirects if successful. 当前版本的action方法在出现问题时将错误添加到ModelState,如果成功则将重定向。

Action method within AdminController.cs: AdminController.cs中的操作方法:

[HttpPost]
public async Task<ActionResult> Create(CreateModel model)
{
    if (ModelState.IsValid)
    {
        AppUser user = new AppUser { UserName = model.Name, Email = model.Email };
        IdentityResult result = await UserManager.CreateAsync(user,
            model.Password);
        if (result.Succeeded)
        {
            return RedirectToAction("Index");
        }
        else
        {
            AddErrorsFromResult(result);
        }
    }
   return View(model);
}

The view: 风景:

@model IdentityDevelopment.Models.CreateModel
@{ ViewBag.Title = "Create User";}

<h2>Create User</h2>
@Html.ValidationSummary(false)
@using (Html.BeginForm("Create", "Admin", new { returnUrl = Request.Url.AbsoluteUri }))
{
    <div class="form-group">
        <label>Name</label>
        @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        <label>Email</label>
        @Html.TextBoxFor(x => x.Email, new { @class = "form-control" })
    </div>
    <div class="form-group">
        <label>Password</label>
        @Html.PasswordFor(x => x.Password, new { @class = "form-control" })
    </div>
    <button type="submit" onclick="return showDiv();" class="btn btn-primary">Create</button>
    @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })


}


<button id="usercreatebutton">Create</button>

As seen above, the button with the "usercreatebutton" id is my development button I want to put the ajax function in: 如上所示,具有“ usercreatebutton” id的按钮是我想将ajax函数放入的开发按钮:

$("#usercreatebutton")
       .button()
       .click(function (event) {
           alert("ajax post call");
       });

The other Create button is for the regular form submit. 另一个“创建”按钮用于常规表单提交。

The CreateModel: CreateModel:

 public class CreateModel
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Email { get; set; }
        [Required]
        public string Password { get; set; }
    }

Based on Shyju's response, I got this working. 根据Shyju的回复,我开始工作了。 Below I will post the updates to my code: 下面,我将更新发布到我的代码中:

In the view, I modified the BeginForm declaration to give the form an id and moved the submit button inside it: 在视图中,我修改了BeginForm声明以为表单提供ID,并在其中移动了Submit按钮:

@model IdentityDevelopment.Models.CreateModel
@{ ViewBag.Title = "Create User";}

<h2>Create User</h2>
@Html.ValidationSummary(false)
@using (Html.BeginForm("Create", "Admin", new { returnUrl = Request.Url.AbsoluteUri }, FormMethod.Post, new { @id = "signupform" }))
{
    <div class="form-group">
        <label>Name</label>
        @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        <label>Email</label>
        @Html.TextBoxFor(x => x.Email, new { @class = "form-control" })
    </div>
    <div class="form-group">
        <label>Password</label>
        @Html.PasswordFor(x => x.Password, new { @class = "form-control" })
    </div>
   <!-- <button type="submit" onclick="return showDiv();" class="btn btn-primary">Create</button> -->

    <button type="submit" id="usercreatebutton">Create</button>
    @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })


}

The controller code was modified to be the one from Shyju's response. 控制器代码已修改为来自Shyju的响应。

Finally, the javascript code was: 最后,JavaScript代码是:

 $("form#signupform").submit(function (event) {
         event.preventDefault();
         var form = $(this);
         $.post(form.attr("action"), form.serialize(), function (res) {
             if (res.status === "success") {
                 alert(res.message);
             }
             else {
                 alert(res.message);
             }
         });

     });

First of all, put your submit button inside the form 首先,将您的“提交”按钮放入表单中

@using (Html.BeginForm("Create", "Admin", new { returnUrl = Request.Url.AbsoluteUri }))
{   
  // Your existing form elements
  <button type="submit" id="usercreatebutton">Create</button>
}

Now listen to the form submit event get the form ,serialize it and send it. 现在听表单submit事件,获取表单,序列化并发送。 You may use jQuery serialize method to do that. 您可以使用jQuery序列化方法来做到这一点。

$.post is a shorthand of $.ajax with POST method type. $.post$.ajax的简写,具有POST方法类型。 Let's use that. 让我们使用它。

$(function(){

  $("form#giveYourFormIdHere" ).submit(function(e) {

     e.preventDefault();
     var form=$(this);
     $.post(form.attr("action"),form.serialize(),function(res){
        //do something with the res
     });

  });

});

Now, in your HttpPost action, Since we are making an ajax call, we should return a JSON response. 现在,在您的HttpPost操作中,由于我们正在进行ajax调用,因此我们应该返回JSON响应。

[HttpPost]
public async Task<ActionResult> Create(CreateModel model)
{
    if (ModelState.IsValid)
    {
        AppUser user = new AppUser { UserName = model.Name, Email = model.Email };
        IdentityResult result = await UserManager.CreateAsync(user,
            model.Password);
        if (result.Succeeded)
        {
            return Json(new { status="success"});
        }
        else
        {                
            return Json(new { status="error",message="Some error"});
        }
    }
    return Json(new { status="error", message="Model validation failed"});
}

Update your $.post method's callback to read this JSON data, inspect the property values and do something. 更新$.post方法的回调以读取此JSON数据,检查属性值并执行某些操作。

$.post(form.attr("action"),form.serialize(),function(res){
        if(res.status==="success")
        {
          window.location.href="/Admin/Index";
        }
        else
        {
          alert(res.message);
        }
});

If you want to support ajax form submit and normal form submit, You may use Request.IsAjaxRequest() method to conditionally return different responses. 如果要支持ajax表单提交和普通表单提交,则可以使用Request.IsAjaxRequest()方法有条件地返回不同的响应。 Also if you want to return the model validation errors, you may read it from the model state and add the needed info(error messages ?) to the JSON response and display that to user. 另外,如果您想返回模型验证错误,则可以从模型状态中读取它,并将所需的信息(错误消息?)添加到JSON响应中并显示给用户。 Here is a post explaining how to read the model errors. 是一篇说明如何读取模型错误的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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