2012-11-21 61 views
0

我遇到了mvc34 razor view中提交按鈕的問題。我在jQuery中向webgrid動態添加了一行,其中包含一個提交按鈕,以在db.中插入行數據。我想驗證行的文本框是否爲空彈出警報並停止操作。 當我試圖寫這樣我們如何防止MVC3中的提交按鈕操作?

$('#btnInsert').click(function() 
{ 
if ($('#tbStudentName').val() == '') { 
       alert('Please enetre!'); 
          return false; 
      } 
}); 

此事件不是在所有jQuery中射擊。 我們可以在上面的jQuery中調用動態創建的提交按鈕客戶端點擊事件嗎? 我寫這樣的

function InsertClick(button) { 
     if ($('#tbStudentName').val() == '') { 
      alert('Please enetre!'); 
         return false; 
     }   
    } 

但仍控制器側FormAction方法燒製。 任何人都可以告訴我解決方案,以防止在服務器端的行動?

回答

0

您可以通過將事件綁定到窗體本身來做到這一點。

$("form").submit(function(e) { e.PreventDefault(); return false; } 

當然,您可以添加一些if語句,以防止在某些情況下。

+0

在這裏,我將輸入解決方案使用動態jQuery.Then怎麼可以這樣寫提交按鈕這條線可能會導致阻止表單中的所有提交按鈕操作。 –

+0

似乎@testCoder已經回答了你的問題?或者你需要額外的信息? – dasheddot

0

或者你也可以使用輸入型按鈕,默認情況下不會引起形式提交,如果驗證成功通過

$(this).parents("form").submit(); 

這裏提交表單是例如:

<script type="text/javascript"> 
    $(function() { 
     $(".go").click(function() { 
      var wrong = true; //fake data 
      if (wrong) { 
       alert("your value is wrong"); 
      } else { 
       $(this).parents("form").submit(); 
      } 
     }); 
    }); 
</script> 

@using(Html.BeginForm()) 
{ 

    @Html.TextBoxFor(x=>x.CompanyName) 
    @Html.ValidationMessageFor(x=>x.CompanyName) 
    <br/> 

    <input type="button" value="go" class="go" /> 
} 

UPDATE

如果您要按鈕添加按鈕,您應該使用jquery live事件Attach an event handler for all elements which match the current selector, now and in the future.

這裏是例子:

<script type="text/javascript"> 
    $(function() { 
     $(".go").live("click", function() { 
      var wrong = true; //fake data 
      if (wrong) { 
       alert("your value is wrong"); 
      } else { 
       $(this).parents("form").submit(); 
      } 
     }); 

     $(".add").click(function() { 
      $("form:first").append("<input type='button' value='go' class='go' />"); 
     }); 

    }); 
</script> 

@using(Html.BeginForm()) 
{ 

    @Html.TextBoxFor(x=>x.CompanyName) 
    @Html.ValidationMessageFor(x=>x.CompanyName) 
    <br/> 


} 


<a class="add" href="#">add button dinamically</a> 
+0

在這裏,我使用jQuery動態添加輸入提交按鈕。然後,如何編寫此代碼?此行可能會導致阻止表單中的所有提交按鈕操作。 –

+0

看看更新的答案。 – testCoder

+0

感謝您的更新回答:-) –

0

我發現這樣

<input type="submit" value="Insert" onclick="return Validate(this);" /> 


function Validate(button){ 
if($('#tbemail').val()==''){ 
    alert('Can't be blank!'); 
    return 1==3; 
} 

}