MVC – Hướng dẫn show Error Message cụ thể khi gọi Ajax

Khi làm web MVC các bạn hay thường gọi Ajax. Nhưng khi có lỗi nó thường không show message cụ thể. Vậy làm thế nào? Hãy đọc tiếp nhé.

Hi all,

Thường thì khi bạn gọi Ajax thì sẽ có trường hợp lỗi nó show ra không cụ thể.

Do đó

Mình sẽ hướng dẫn bạn cách xử lý show Lỗi cụ thể khi mình gọi 1 request Ajax.

Controller

public ActionResult MyAjaxCall()
{
	try
	{
	   // Your code here
	}
	catch (Exception ex)
	{
		Logging.Logger.LogError(ex);
		// Show message to screen
		Response.StatusCode = (int)HttpStatusCode.BadRequest;
		return Content(ex.Message, MediaTypeNames.Text.Plain);
	}
}

 

MasterView

<script type="text/javascript">
    $(document).ready(function () {
		// Handle Error When Ajax Call
		$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
			// By pass if F5 many times
			if ((jqXHR.statusText == 'error')) {
				return;
			}
			// Show error
			$("#main-content").html('');
			$("#main-content").html(jqXHR.statusText + '<br/><br/> An unexpected error occured on our website. Please contact Admin to support.' + jqXHR.responseText);
		});
	});
</script> 

 

F G+ T

tuandph

Khởi đầu với .NET từ năm 2013 đến nay. Hiện tại mình đang làm full-stack developer. Yêu thích lập trình & chia sẽ kiến thức. Thời gian rảnh thường làm những tool vui vui và viết lách kể lệ sự đời.

Leave a Reply

We're glad you have chosen to leave a comment. Your email address is required but will not be published.
  • Không nói tục
  • Không chửi bậy
  • Comment ko hài hước không support