2013-06-06 4 views
4

MVC4에서 작업하고 JQuery 및 JSON을 사용하여 값 형식보기를 컨트롤러로 전달하려고합니다. 쿼리는 표 안의 체크 상자 값을 추출합니다. 되는 다음 코드 :jQuery/JSON 오류 "SyntaxError : JSON.parse : unexpected character"

<script type="text/javascript"> 
function DeleteCustomer() { 
    var temp = ""; 
    var id = ""; 

    if (confirm("Are you sure to delete records?")) { 
     $('#myGrid table tr').each(function() { 
      if ($(this).find("input[id*='assignChkBx']").length > 0) { 
       if ($(this).find("input[id*='assignChkBx']")[0].checked == true) { 
        temp = $(this).find("input[id*='assignChkBx']").val(); 
        if (temp != "" || temp != null) { 
         id = id + " " + temp; 
         temp = ""; 
        } 
       } // End of Loop 
      } 
     }); //End of each Loop 
     $.ajax({ 
      url: "Customer/DeleteCustomeByID", 
      type: "POST", 
      contentType: 'application/json; charset=utf-8', 
      dataType: "json", 
      data: "{'CustomerID':'" + id + "'}", 
      success: function (data) { 
       //alert('Records deleted'); 
       $('#lblMessage').html('Records Deleted'); 
      }, 
      error: function (xhr, textStatus, err) { 
       alert('Error: ' + err); 
       //$('#lblMessage').html(err); 
      } 
     }); 
    } 
} 

내 HTML 코드는 다음입니다 : 내가 삭제 버튼을 클릭하면

<input type="button" id="btnDelete" value="Delete" title="Delete" onclick="DeleteCustomer()" style="color: Gray" /> 


@{ 
    WebGrid grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid"); 
} 
@grid.GetHtml(
    fillEmptyRows: false, 
    alternatingRowStyle: "alternate-row", 
    headerStyle: "grid-header", 
    footerStyle: "grid-footer", 
    mode: WebGridPagerModes.All, 
    firstText: "<< First", 
    previousText: "< Prev", 
    nextText: "Next >", 
    lastText: "Last >>", 
    columns: new[] { 
     grid.Column("", format: @<text><input class="check-box" type="checkbox" id="assignChkBx" value="@item.CustomerID" /></text>), 
     grid.Column("CustomerID", "CustomerID", canSort: true), 
     grid.Column("CompanyName", "Company Name", canSort: true), 
     grid.Column("ContactName", "Contact Name", canSort: true), 
     grid.Column("Address", "Address", canSort: false), 
     grid.Column("City", "City", canSort: true), 
     grid.Column("", 
        header: "Actions", 
        format: @<text> 
        @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID}) 
        @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID}) 
        </text> 
     ) 
}) 

위에서 언급 한 JQuery와 소요 선택한 값을 컨트롤러로 전송합니다. 컨트롤러 코드는 아래에 기록됩니다 내가 삭제 버튼을 클릭하면

[HttpPost] 
    public ActionResult DeleteCustomeByID(string CustomerID) 
    { 
     Customer customer = new Customer(); 
     try 
     { 
      if (ModelState.IsValid) 
      { 
       string[] values = CustomerID.Split(' '); 

       for (int i = 1; i <= values.Length - 1; i++) 
       { 
        if (values[i].ToString().Trim() != "" || values[i].ToString() != null) 
        { 
         customer = db.Customers.Find(values[i].ToString()); 
         db.Customers.Remove(customer); 
         db.SaveChanges(); 
        } 
       } 
       return RedirectToAction("Index"); 
      } 
      return View(customer); // Error in Model, if any 
     } 
     catch (DbEntityValidationException dbEx) 
     { 
      foreach (var validationErrors in dbEx.EntityValidationErrors) 
      { 
       foreach (var validationError in validationErrors.ValidationErrors) 
       { 
        Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}", 
         validationErrors.Entry.Entity.GetType().FullName, 
         validationError.PropertyName, 
         validationError.ErrorMessage); 
       } 
      } 

      throw new Exception(); // You can also choose to handle the exception here... 
     } 
     catch (Exception ex) 
     { 
      throw new Exception(ex.Message); 
     } 
    } 

, 값이 기록을 컨트롤러 및 삭제로 이동합니다. 사파리 "JSON 구문 분석 오류 알 수없는 토큰 '<'"파이어 폭스 "예상치 못한 문자구문 에러 : : : JSON.parse"그러나 문제는 다시 컨트롤러에, 나는 다음과 같은 오류를 얻고 때 기록을 삭제 한 후,이다 및 "오류 : 개체 오류" 나는 다양한 사이트를 검색하고 다양한 솔루션을 시도합니다. 그러나 아무것도 작동하지 않습니다. Northwind db를 사용하고 있습니다.

미리 감사드립니다. the docs, 다음 특성에 따라 파르

답변

11

:

dataType: "json" 

은 ... jQuery를 당신이 다시 서버에서 기다리고있어 데이터의 유형을 알려줍니다. 그런 다음 HTML이 반환됩니다. 따라서 jQuery가 JSON 구문 분석을 시도 할 때 예상대로 HTML로 실행되고이 오류가 발생합니다.

JsonResult을 반환하거나 dataType"html"으로 설정하여 작업을 변경하십시오.

+0

감사합니다. StriplingWarrior. 귀하의 제안이 효과가 있습니다. 오류없이 선택한 데이터를 삭제합니다. 그러나 문제는 인덱스 페이지로 돌아가서 페이지를 새로 고칠 때까지 삭제 된 데이터가 체크 된 표시로 남아있을 때입니다. 어떤 단서가 있습니까? 다시 한번 감사드립니다. – Partha

+0

@Partha : 예. AJAX 호출을 사용하고 있으며 호출 된 동작이 뷰를 반환하지만 AJAX 콜백은 반환 된 데이터를 사용하지 않고 수행합니다. 일반적으로 전체보기가 브라우저에 의해 렌더링 될 것으로 예상되는 경우 비 아약스 게시물 (http : // stackoverflow)을 수행 할 수 있습니다.com/a/5524053/120955). 그렇지 않으면 체크 박스 값을 직접 변경하거나 컨트롤러 동작에서 부분 뷰를 반환하고 페이지의 일부를 반환 된 HTML로 교체하여 성공 콜백이 새 정보로 페이지를 수정하는 방법을 파악합니다. – StriplingWarrior

0

확실하지,하지만 난 당신이 $ 아약스 호출에서 JSON을 통과하지 않을 알아 차렸다 ...보십시오 :

data: JSON.stringify({CustomerID: id }), 
... 

JSON은 멤버 이름 주위에 따옴표를 사용합니다.

0

이 미친 오류에 대한 솔루션을 검색, 테스트 및 디버깅 한 후, 문제가 jquery 라이브러리라는 것을 알게되었습니다. 새 프로젝트를 시작하면서 최근 jquery-1.10.2.js를 선택하고 오류가 발생했습니다. Jquery-1.9.1.js를 시도했으며 오류도 발생했습니다. 하지만 jquery-1.5.2.js로 테스트했을 때 성공 함수가 제대로 작동하고 오류가 발생하지 않았습니다.

+0

하지만 최신 버전은 무엇입니까? –

+0

나는 어떤 이유로 jquery-1.10.2.js가 최신이라는 것을 발견했지만, 올바르게 기억하지 못합니다. – prosa

관련 문제