2015-12-31 19 views
0

在我的網頁我有這樣一段:MVC使用jQuery,而不是提交按鈕

using (Html.BeginForm("AddSubTor", "Maintor", FormMethod.Post, htmlAttributes: new { ID = "frmSubTors" })) 
{ 
    @Html.AntiForgeryToken() 

    @Html.Partial("_SublistPartial") 

    <div class="row" style="margin-top: 15px;"> 
    <div class="col-sm-12 col-md-12 col-lg-12 text-center "> 
     @* submit button here *@ 
     <input type="submit" class="btn btn-default" value="Add" /> 
    </div> 
    </div> 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
} 

而不是使用提交按鈕,我會看起來像一個按鈕的圖像替換它的話,可能我也做同樣的提交在jquery函數中。就像那個按鈕式圖像的點擊事件一樣?我提交的數據是否仍會提交?

我想這樣做的原因是,在部分我有兩個單選按鈕。在這兩個我有一些Jquery代碼來檢索數據和其他東西。

如果我使用簡單的提交按鈕,我可以設置單選按鈕但沒有點擊事件,因此數據不會被檢索,其他的東西沒有完成。 因此,如果我可以使用Jquery,那麼我可以簡單地調用單選按鈕事件調用的函數,並獲取我的數據。

[編輯] 我有種找這樣的事情:

$.Ajax({ 
    url: 'controller/action', 
    type: 'POST', 
    success: function(data) { 
    $('#frmSubTors').html(data); 
    } 
}).done(function() { 
    // do my other stuff here 
}); 

將這項工作呢?

+0

我不遵循你的推理。 'type =「submit」'按鈕不需要'onclick'事件,它會將表單值發佈到您的操作中。你最後一段有些模糊。 –

+0

更新了問題 – Eric

回答

1

是的,如果你使用$('#frmSubTors').submit(),表格將被提交所有的領域。

3

是的,您可以使用jQuery在單擊圖像時提交表單。 用圖像替換提交按鈕並給它一個id。

<div class="col-sm-12 col-md-12 col-lg-12 text-center "> 
     @* submit button here *@ 
     <img id="myImage" src="blah.jpg" /> 
</div> 

然後讓jQuery的響應click事件:

$(document).ready(function() { 
    $("#myImage").click(function() { 
     $("#frmSubTors").submit(); 
    } 
} 

更多jQuery的單擊事件信息:http://www.w3schools.com/jquery/event_click.asp

+0

但是我可以在提交完成並更新部分後執行任何功能嗎?和.Ajax一樣,你有一個Done事件在數據返回後觸發,然後Jquery腳本繼續。這也可能嗎? – Eric

1

你可以使用你的圖像事件提交表單。

$('img').on("click", function() { 
    $('#frmSubTors').submit(); 
}); 
1

你可以用下面的ajax提交form

$("#your_img_id").click(function() { 
    $.ajax({ 
     type: 'POST', 
     url: '/Maintor/AddSubTor', 
     data: $(this).serialize(), //serializes the form's elements. 
     success: function (data) { 
      // do your other stuff here after succesful form submit 
     } 
    }); 
}); 

如果您form<input type="file">然後執行以下一樣。

$("#your_img_id").click(function() { 
    var formData = new FormData($('#frmSubTors')[0]); 

    $.ajax({ 
     type: 'POST', 
     url: '/Maintor/AddSubTor', 
     data: formData, 
     cache: false, 
     contentType: false, 
     processType: false, 
     success: function(data) { 
      // do your other stuff here after succesful form submit 
     } 
    }); 
}); 

希望這會對你有幫助。

+0

謝謝。這確實有點幫助我。 formdata需要序列化,但後來我得到了一個新問題,即防僞標記。在這裏找到了解決方案:http://stackoverflow.com/questions/14473597/include-antiforgerytoken-in-ajax-post-asp-net-mvc – Eric

相關問題