2016-04-20 30 views
-1

我有一個複雜功能來顯示ValidationMessageFor或mvc範圍,我有一個ajax方法來檢查一個id bd並且它返回一個布爾值,如果需要這個結果,這個結果。如何顯示ValidationMessageFor來自js

function ExistProduct() { 

    $.ajax({ 
     type: 'GET', 
     url: "/Products/ExistProduct", 
     contentType: "application/json;charset=utf-8", 
     data: JSON.stringify({ "id": id }), 
     datatype: "json", 
     success: function (data) { 
      if (data.exist == true) { 
       // show ValidationMessageFor 
      } 
      else { 

      } 
     } 
    }); 
} 

,我可以解決此,不允許提交申請並保存

+0

您是否想驗證產品是否存在?如果是這樣,請使用RemoteAttribute [如何:在ASP.NET MVC中實現遠程驗證](https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx)。不要試圖重新發明輪子 –

回答

0

你的函數

function ExistProduct() { 

    $.ajax({ 
     type: 'GET', 
     url: "/Products/ExistProduct", 
     contentType: "application/json;charset=utf-8", 
     data: JSON.stringify({ "id": id }), 
     datatype: "json", 
     success: function (data) { 
      if (data.exist == true) { 
       // show ValidationMessageFor 
       jQuery("#valodation_msg").css({"color":"green"}); 
       jQuery("#valodation_msg").html("Success"); 
      } 
      else { 
       jQuery("#valodation_msg").css({"color":"red"}); 
       jQuery("#valodation_msg").html("Error"); 
       return false; 
      } 
     } 
    }); 
} 

增加一個檔位,你的HTML代碼中要顯示的驗證味精

<div id="valodation_msg"></div> 
+0

你好,謝謝,但不允許提交,這是可能的嗎? –

+0

yes .. add「return false;」低於錯誤消息。 –

+0

如果我提交這是我的代碼'@ Html.EditorFor(model => model.ProductID,new {htmlAttributes = new {id =「txtProductoid」,@ class =「form-control」}}) @ Html.ValidationMessageFor model => model.ProductID,「」,new {@class =「text-danger」})

' –

0
function ExistProduct() { 

$.ajax({ 
    type: 'GET', 
    url: "/Products/ExistProduct", 
    contentType: "application/json;charset=utf-8", 
    data: JSON.stringify({ "id": id }), 
    datatype: "json", 
    success: function (data) { 
     if (data.length > 0) { 
      // show ValidationMessageFor 
     var p = document.createElement('p'), 
     txt = document.createTextNode("Your validation message"); 
     p.appendChild(txt); 
     document.getElementById("id of the element where u want to show validation message ").appendChild(p); 
     return false; 

     } 
     else { 

     } 
    } 
}); 

}