![](/img/trans.png)
[英]How to call MVC Action using Jquery AJAX and then submit form in MVC?
[英]How to submit form using Ajax in MVC
我在將表單數據保存在數據庫中時遇到問題。 我在下面顯示的代碼上完成了小代碼,當我在表單中輸入數據並單擊我的提交按鈕時,它不起作用。
$(".btn").click(function(e) { e.preventDefault(); var form = $("#frm"); $.ajax({ url: '/Form/Index', data: form.serialize(), type: 'POST', success: function(data) { } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form role="form" id="frm"> <div class="form-group"> <div class="col-sm-6 col-lg-12 col-md-12"> <div class="form-group"> <label for="name" style="color:black;">Product Name</label> <input type="text" class="form-control" id="name" placeholder="Product Name" style="color:black;"> </div> <div class="form-group"> <label for="name" style="color:black;">Product Date</label> <input type="text" class="form-control" id="Text1" placeholder="Date" style="color:black;"> </div> <div class="form-group"> <label for="name" style="color:black;">Product Price</label> <input type="text" class="form-control" id="Text2" placeholder="Date" style="color:black;"> </div> </div> </div> <button type="submit" class="btn btn-default" id="ok" >Submit</button> </form>
以上是我的代碼,請給我解決方案
我檢查了您的代碼后,客戶端代碼工作正常,在這種情況下,我能想象的唯一問題是url path
。
確保您提供正確的url path
。
您應該檢查其是否到達該頁面。
您正在使用哪個框架。 不同的框架具有不同的語法以在URL中傳遞值。 在URL參數中檢查在頁面源頁面視圖中獲取的路徑,或者可以在提交后在控制台日志中檢查錯誤。 可能無法正確執行操作。
從按鈕中刪除type =“ submit”
您必須獲取具有ID的表單提交並序列化表單數據`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`
確保ajax庫已成功加載,並嘗試發出警報消息以將到達的轉發步驟進行以下測試:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
如果未執行beforeSend,則您的問題與ajax庫有關。
用這個 :
$("#ok").click(function(e) {
// your code
}
請參考javascript中的id而不是class屬性。 如果您引用的類屬性超過一次,則單擊javascript對該類執行preventDefault,這樣,如果不刷新您的頁面,則該按鈕不起作用。
將preventDefault函數放在函數的最后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.