如何使用Ajax调用此后操作方法? [英] How to call this post action method using Ajax?

查看:85
本文介绍了如何使用Ajax调用此后操作方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个表单,该表单执行Ajax发布以创建新用户.我的目标是显示一个指示操作结果的弹出窗口.当前版本的action方法在出现问题时将错误添加到ModelState,如果成功则将其重定向.

I am trying to create a form that does an Ajax post for a creation of a new user. 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.

AdminController.cs中的操作方法:

Action method within 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);
}

视图:

@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>

如上所示,具有"usercreatebutton" id的按钮是我想将ajax函数放入以下位置的开发按钮:

As seen above, the button with the "usercreatebutton" id is my development button I want to put the ajax function in:

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

另一个创建"按钮用于常规表单提交.

The other Create button is for the regular form submit.

CreateModel:

The CreateModel:

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


根据Shyju的回复,我开始工作了.下面,我将更新发布到我的代码中:


Based on Shyju's response, I got this working. Below I will post the updates to my code:

在视图中,我修改了BeginForm声明以为表单提供ID,并在其中移动了提交按钮:

In the view, I modified the BeginForm declaration to give the form an id and moved the submit button inside it:

@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" })


}

控制器代码已修改为Shyju的响应.

The controller code was modified to be the one from Shyju's response.

最后,javascript代码是:

Finally, the javascript code was:

 $("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>
}

现在监听表单submit事件,获取表单,将其序列化并发送.您可以使用jQuery序列化方法来做到这一点.

Now listen to the form submit event get the form ,serialize it and send it. You may use jQuery serialize method to do that.

$.post$.ajax的简写,具有POST方法类型.让我们使用它.

$.post is a shorthand of $.ajax with POST method type. 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
     });

  });

});

现在,在您的HttpPost操作中,由于我们正在进行ajax调用,因此我们应该返回JSON响应.

Now, in your HttpPost action, Since we are making an ajax call, we should return a JSON response.

[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"});
}

更新您的$.post方法的回调以读取此JSON数据,检查属性值并执行某些操作.

Update your $.post method's callback to read this JSON data, inspect the property values and do something.

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

如果要支持ajax表单提交和普通表单提交,则可以使用Request.IsAjaxRequest()方法有条件地返回不同的响应.另外,如果您想返回模型验证错误,则可以从模型状态中读取它,并将所需的信息(错误消息?)添加到JSON响应中,并将其显示给用户. 此处是一则帖子,解释了如何读取模型错误

If you want to support ajax form submit and normal form submit, You may use Request.IsAjaxRequest() method to conditionally return different responses. 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. Here is a post explaining how to read the model errors.

这篇关于如何使用Ajax调用此后操作方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆