2016-07-19 18 views
1

현재 내가 할 수있는 ASP.NET에서 AJAX를 사용하여 모델을 생성하지만 않는 나는 settingProfile JS 객체에 싸여 데이터를 전송하는 AJAX를 사용하려고하면 그것은 HTTP 500 내부 서버 오류 오류를 반환, 나는 데이터 유형에 문제가 있다고 생각합니다. AJAX에서 Create 메서드를 호출하는 올바른 방법은 무엇입니까?어떻게</p> <p>을 (SettingProfile를 이동하여/만들기) 정기적으로 모델을 만들 수 MVC 5

내 코드 :

모델 :

public class SettingProfile 
    { 
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public long? UserId { get; set; } 
     public string Url { get; set; } 
    } 

보기 (JS) :

function saveSettingProfile() { 
     var name = prompt("Please enter profile name", ""); 
     var url = $("form").serialize(); // Not AJAX url, its a variable in model 

     var settingProfile = { 
      Name: name, 
      Url: url 
     }; 

     jQuery.ajax({ 
      url: "@Url.Action("Create", "SettingProfile")", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      method: "POST", 
      data: settingProfile 
     }).done(function (response) { 
      alert("Profile saved successfully"); 
     }).fail(function() { 
      alert("Could not save profile"); 
     }); 
    } 

컨트롤러

:

 [HttpPost] 
     //[ValidateAntiForgeryToken] 
     public ActionResult Create([Bind(Include = "Name,Url")] SettingProfile settingProfile) 
     { 
      settingProfile.UserId = 8; // TODO: get user id from session 
      if (ModelState.IsValid) 
      { 
       db.SettingProfiles.Add(settingProfile); 
       db.SaveChanges(); 
       return Json(new { success = true }); 
      } 
      return Json(new { success = false }); 
     } 
+1

HTTP 상태가 500이면 예외 메시지는 무엇입니까? – Anton

+0

Ajax.BeginForm 메서드를 사용할 수없는 이유는 무엇입니까? – Xavr

답변

1

500 오류가 의미 서버 코드가 충돌한다 . 그것은 여러 가지 이유가있을 수 있습니다. 내가 알아챈 한 가지는 (500 오류가 발생할 수 있음) 데이터를 보내는 방식입니다.

"application/json"으로 contentType을 지정했습니다. 그러나 javascript 객체를 그대로 보냅니다. 따라서 요청 페이로드는 다음과 같이 전송됩니다.

Name=SomeNameValue&Url=SomeUrlValue 현재 서버 코드에서 모델 바인더는 SettingProfile의 개체에 매핑 할 수 없습니다.

해결 방법은 자바 스크립트 개체의 문자열 버전을 보내는 것입니다. 이렇게하려면 JSON.stringify 메서드를 사용할 수 있습니다.

jQuery.ajax({ 
       url: "@Url.Action("Create", "SettingProfile")", 
       contentType: "application/json; charset=utf-8", 
       method: "POST", 
       data: JSON.stringify(settingProfile) 
     }).done(function (response) { 
      alert("Profile saved successfully"); 
     }; 

이제 클라이언트 코드가 제대로 매핑 할 수있을 것입니다

{"Name":"SomeName","Url":"SomeUrl"} 

및 모델 바인더와 같은 요청 페이로드를 보낼 것입니다.

단순한 데이터 인 경우 사용자 정의 contentType을 언급하지 않고 js 객체를 그대로 전송할 수 있습니다. jQuery는 "application/x-www-form-urlencoded"라는 기본 contentType 값을 사용하고 모델 바인딩이 작동합니다.

그래서 아래 코드는 정상적으로 작동합니다.

jQuery.ajax({ 
       url: "@Url.Action("Create", "SettingProfile")", 
       method: "POST", 
       data:settingProfile 
     }) 

또한 브라우저의 네트워크 탭을 확인하고 아약스 호출에 대해 다시 서버에서 오는 응답을 볼 수 있습니다. 예외가 발생하면 세부 정보를 볼 수 있습니다.

+1

감사합니다. 작동합니다! – Yustx

+0

@Yustx 처음에 승인되었습니다. (신중하게 읽어야하고) 편집을 롤백했습니다. JSON.stringify는 필요하지 않습니다. 만들려는 전체적인 요점은 코드가 없어도 작동한다는 것입니다. – Shyju