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, 다음 특성에 따라 파르
감사합니다. StriplingWarrior. 귀하의 제안이 효과가 있습니다. 오류없이 선택한 데이터를 삭제합니다. 그러나 문제는 인덱스 페이지로 돌아가서 페이지를 새로 고칠 때까지 삭제 된 데이터가 체크 된 표시로 남아있을 때입니다. 어떤 단서가 있습니까? 다시 한번 감사드립니다. – Partha
@Partha : 예. AJAX 호출을 사용하고 있으며 호출 된 동작이 뷰를 반환하지만 AJAX 콜백은 반환 된 데이터를 사용하지 않고 수행합니다. 일반적으로 전체보기가 브라우저에 의해 렌더링 될 것으로 예상되는 경우 비 아약스 게시물 (http : // stackoverflow)을 수행 할 수 있습니다.com/a/5524053/120955). 그렇지 않으면 체크 박스 값을 직접 변경하거나 컨트롤러 동작에서 부분 뷰를 반환하고 페이지의 일부를 반환 된 HTML로 교체하여 성공 콜백이 새 정보로 페이지를 수정하는 방법을 파악합니다. – StriplingWarrior