2012-08-30 59 views
0

我需要從控制器發送一個錯誤消息,以防ajax函數中發生錯誤。 這裏是我的控制器代碼:從控制器發送字符串到錯誤ajax函數MVC3

//check if the day is already approved 
string check1 = "SELECT approve_status_id FROM table_approvals WHERE approve_date=" + date + " AND user_id=" + Session["userID"]; 
MySqlCommand status_cmd = new MySqlCommand(check1, con); 
MySqlDataReader rdrStatus = status_cmd.ExecuteReader(); 
while (rdrStatus.Read()) 
{ 
    if (rdrStatus.GetString(0) == "5") 
    { 
     valid = false; 
     error = "You cannot edit already approved dates!"; 
     response.Message = error; 
    return View(Json(new { success = false,error},JsonRequestBehavior.AllowGet)); 
    } 
} 

我AJAX功能:

$.ajax({ 
    url: '@Url.Action("SaveLine", "AddLine")', 
    type: 'post', 
    data: { ids: IDs }, 
    dataType: 'json', 
    traditional: true, 
    success: function() { 
     window.location.href = '@Url.Action("Index", "AddLine")'; 
    }, 
    error: function() { 
     $.getJSON('/AddLine/SaveLine', function (json) { 
      alert('error'); 
      $("#ajaxPostMessage").html(json.Message); 
     }); 
+0

您可能想了解[SQL Injection](http://www.securiteam.com/securityreviews/5DP0N1P76E.html) –

回答

0

裹一切都在嘗試捕捉。您可以簡單地調用JSON方法,該方法將創建JSON響應並將其返回給客戶端代碼。此外,當它是一個HttpPost操作方法時,您不需要JsonRequestBehavior.AllowGet來返回JSON。你需要爲GET只。($.getJSON, $.get ..

try 
{ 
    //code for getting data to reader  
    while (rdrStatus.Read()) 
    { 
     if (rdrStatus.GetString(0) == "5") 
     { 
      valid = false; 
      var errorMsg = "You cannot edit already approved dates!";    
      return Json(new { success = false,Error=errorMsg });   
     } 
    } 
} 
catch(Exception ex) 
{ 
    //log Error 
    return Json(new { success = false,Error="Some Error!"}); 
} 

這將在您的客戶端代碼返回一個JSON像這樣的客戶現在

{ "success ": "True", "Error": "SomeError" } 

,您可以檢查JSON,做任何你想要的。

success: function (data) { 
    if(data.success=="True") 
    { 
     window.location.href = '@Url.Action("Index", "AddLine")'; 
    } 
    else 
    { 
     alert(data.Error); 
    } 
}, 
+1

謝謝!那很棒! – taia

+0

@taia:不客氣。很高興我能幫上忙 :) – Shyju

相關問題