繁体   English   中英

jQuery将表单的commit()提交给控制器中的操作,然后将一个对象返回给客户端,而不是重新加载页面

[英]Jquery form submit() to the action in the controller then returns an object to the client and not reload page

我想要在jQuery中调用Submit()函数之后。 它将执行操作以处理逻辑,然后该操作会将对象返回给客户端,因此客户端将其显示。

我尝试了很多方法,但是没有,请帮助我。

我有这样的形式:

<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
  First name:<br>
  <input type="text" name="firstname" value="Mickey">
  <br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse">
  <br><br>
</form> 
<button class="btn btn-success" type="button" onclick="Save()">Save</button>

我想尝试Code Js:

function Save(
  $("#myform").submit(function (eventData, handler) {
    var resultFromAction = ???
    // I would like to get the object from the action returned
  });
)

要么

function Save(
  var resultFromAction =  $("#myform").submit(); 
  // I would like to get the object from the action returned
)

控制器中的代码操作:

public class MyControllerController: Controller {
  [Authorize]
  public ActionResult Save(FormObject formobj) {
    // do something
    var resultForClient = new {
      phone: "098989878",
      name: "john",
      add: "My address"
    };
    return Json(resultForClient, JsonRequestBehavior.AllowGet);
  }
}

首先,您应该将<button>放在<form> ,并将其type更改为submit

<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
  First name:<br />
  <input type="text" name="firstname" value="Mickey"><br />

  Last name:<br />
  <input type="text" name="lastname" value="Mouse"><br /><br />

  <button class="btn btn-success" type="submit">Save</button>
</form> 

然后,您可以将事件处理程序直接附加到formsubmit事件,以使用jQuery的$.ajax()方法发送AJAX请求:

$("#myform").submit(function(e) {
  e.preventDefault(); // stop the standard form submission
  $.ajax({
    url: this.action,
    type: this.method,
    data: $(this).serialize(),
    success: function(data) {
      console.log(data); // the object returned from your Action will be displayed here.
    }
  });
});

暂无
暂无

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

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