如何从javascript调用Action方法?

时间:2011-10-14 13:29:56

标签: jquery asp.net-mvc

我有一个按钮,提示用户他的动作(删除smth)。如果用户确认,我想用ActionMethod执行postback。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

是的,这很简单,你可以这样做

<强> JS

$('#id-of-your-button').click(function() {
    if(confirm('Are you sure'))
         document.location = '/controller/action/id_to_delete';
});

或使用回发

$('#id-of-your-button').click(function() {
  if(!confirm('Are you sure'))
       return false;
});

如果您的按钮不是提交按钮,则可以这样做

$('#id-of-your-button').click(function() {
      if(confirm('Are you sure'))
           $('#id-of-your-form').submit();
      return false;
    });

如果您没有任何内容(表单和提交按钮)

$('#id-of-your-button').click(function(){
  $.ajax({ url: '/controller/action', 
    dataType: 'html', 
    data: { id_to_delete: $('#where_are_you_holding_your_value').val() },
    type: 'post', 
    success: function(data) {
       alert('your item is deleted');
    }
});