2014-10-28 2 views
41

Я хотел бы контролировать, когда ответ сообщение об ошибке и, когда сообщение об успешном выполнении, но я всегда получаю сообщение об ошибке:Jquery Ajax, вернуть успех/ошибка от контроллера mvc.net

вот что я пытаясь сделать:

$.ajax({ 
       type: "POST", 
       data: formData, 
       url: "/Forms/GetJobData", 
       dataType: 'json', 
       contentType: false, 
       processData: false, 

       success: function (response) {      
        alert("success!") 
       }, 
       error: function (response) { 
        alert("error") // I'm always get this. 
       } 

      }); 

контроллер:

  [HttpPost] 
      public ActionResult GetJobData(Jobs jobData) 
      { 

       var mimeType = jobData.File.ContentType; 
       var isFileSupported = AllowedMimeTypes(mimeType); 

      if (!isFileSupported){   
        // Error 
        Response.StatusCode = (int)HttpStatusCode.BadRequest; 
        return Content("The attached file is not supported", MediaTypeNames.Text.Plain);  
      } 
      else 
       { 
        // Success 
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Content("Message sent!", MediaTypeNames.Text.Plain);  

       } 

      } 
+0

Добавить 'if' состояние ... Я не уверен, что ответ вы ожидаете здесь. –

+0

Ваша ошибка, потому что код после первого оператора возврата не запускается. Вы можете переместить код после комментария для успеха, перед предыдущим оператором return. – Collins

+0

У меня вопрос. теперь мой вопрос ясен. – Eyal

ответ

75
$.ajax({ 
    type: "POST", 
    data: formData, 
    url: "/Forms/GetJobData", 
    dataType: 'json', 
    contentType: false, 
    processData: false,    
    success: function (response) { 
     if (response.success) { 
      alert(response.responseText); 
     } else { 
      // DoSomethingElse() 
      alert(response.responseText); 
     }       
    }, 
    error: function (response) { 
     alert("error!"); // 
    } 

}); 

Контроллер:

[HttpPost] 
public ActionResult GetJobData(Jobs jobData) 
{ 
    var mimeType = jobData.File.ContentType; 
    var isFileSupported = AllowedMimeTypes(mimeType); 

    if (!isFileSupported){   
     // Send "false" 
     return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet); 
    } 
    else 
    { 
     // Send "Success" 
     return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet); 
    } 
} 

--- Дополнение: ---

в основном вы можете отправить несколько параметров, таким образом:

Контроллер:

return Json(new { success = true, 
       Name = model.Name, 
       Phone = model.Phone, 
       Email = model.Email         
      }, 
      JsonRequestBehavior.AllowGet); 

Html:

<script> 
    $.ajax({ 
       type: "POST", 
       url: '@Url.Action("GetData")', 
       contentType: 'application/json; charset=utf-8',    
       success: function (response) { 

        if(response.success){ 
         console.log(response.Name); 
         console.log(response.Phone); 
         console.log(response.Email); 
        } 


       }, 
       error: function (response) { 
        alert("error!"); 
       } 
      }); 
+1

'contentType: 'application/json; charset = utf-8'' или 'false'? И почему? –

+0

отличное решение спасибо –

+0

меня добавил contentType: 'application/json; charset = utf-8 ', processData: false, и это сработало для меня. –

15

Использованиекласс вместо Content, как показано следующее:

// When I want to return an error: 
    if (!isFileSupported) 
    { 
     Response.StatusCode = (int) HttpStatusCode.BadRequest; 
     return Json("The attached file is not supported", MediaTypeNames.Text.Plain); 
    } 
    else 
    { 
     // When I want to return sucess: 
     Response.StatusCode = (int)HttpStatusCode.OK; 
     return Json("Message sent!", MediaTypeNames.Text.Plain); 
    } 

Также установлено CONTENTTYPE:

contentType: 'application/json; charset=utf-8', 
+0

'contentType: 'application/json; charset = utf-8'' или 'false'? И почему? –

+2

Мне нравится этот ответ для обеспечения примера набором 'Response.StatusCode'. –

+0

@ClintEastwood contentType - это тип данных, которые вы отправляете, поэтому его нужно установить в json, очень распространенным является приложение/json; кодировка = UTF-8' . –

Смежные вопросы