2011-11-08 16 views
5

में अपवाद संदेश मिलता है मैं एक कार्य है यह करो ? जब मैं डीबगर से जांचता हूं तो मुझे अपनी स्ट्रिंग दिखाई नहीं देती है।ASP.NET MVC अजाक्स

उत्तर

8

त्रुटि विशेषता लागू करना एक अच्छा तरीका है। इसके अलावा, मैं आमतौर पर अपवाद फेंक नहीं देता, लेकिन त्रुटि के अनुसार status code लौटाता हूं। आप XMLHttpRequest.responseText के माध्यम से अपनी प्रतिक्रिया स्ट्रीम और js में उपयोग करने के लिए लिख सकते हैं:

if (model.MyCondition == true) 
{ 
    if (Request.IsAjaxRequest()) 
    { 
     Response.StatusCode = 406; // Or any other proper status code. 
     Response.Write("Custom error message"); 
     return null; 
    } 
} 

और js में:

... 
error: function (xhr, ajaxOptions, errorThrown) { 
    alert(xhr.responseText); 
} 
0

एक जीईटी प्रकार की कार्रवाई के साथ अपने कार्य से ContentResult लौटने का प्रयास करें।

[HttpGet] 
public ContentResult MyAction(String variablename) 
{ 
    ... 
    if (some_verification == true) 
     return Content("MyMessage); 
    .... 
} 

आपके विचार पृष्ठ पर,

$.ajax({ 
    url: 'your controller/action url', 
    type: 'get', 
    cache: false, 
    async: false, 
    data: { variablename: "value" }, 
    success: function (data) { 
     alert(data); 
    }, 
    error: function() { 
     alert('Error doing some work.'); 
    } 
}); 
+0

प्रश्न नियंत्रक में अपवाद फेंकने से स्ट्रिंग प्राप्त करने के तरीके को –

+0

आह दाएं कॉल को बदलने का तरीका नहीं है। धन्यवाद। – Muthu

0

मैं इस एक कस्टम ErrorAttribute को लागू करने से हल किया है:

[NonAction] 
protected void OnException(ExceptionContext filterContext) 
{ 

    this.Session["ErrorException"] = filterContext.Exception; 

    if (filterContext.Exception.GetType() == typeof(MyException)) 
    { 
     // Mark exception as handled 
     filterContext.ExceptionHandled = true; 
     // ... logging, etc 
     if (Request.IsAjaxRequest()) 
     { 
      /* Put your JSON format of the result */ 
      filterContext.Result = Json(filterContext.Exception.Message); 
     } 
     else 
     { 
      // Redirect 
      filterContext.Result = this.RedirectToAction("TechnicalError", "Errors"); 
     } 
    } 
} 

और फिर इसे साथ अपने कार्यों को सजाने।

आप अपने नियंत्रक की ऑनएक्सप्शन विधि को ओवरराइड भी कर सकते हैं, लेकिन मुझे लगता है कि कस्टम विशेषता अधिक लचीला है।

0

एक संभावना एक BaseController वर्ग जहां नियंत्रक OnException(ExceptionContext filterContext) विधि ओवरराइड और कन्वर्ट बनाने के लिए किया जा सकता है जावास्क्रिप्ट क्लाइंट से आसानी से संसाधित करने में सक्षम होने के लिए JSON में अपवाद।