jQuery / JSON错误“SyntaxError:JSON.parse:unexpected character”

我正在研究MVC4并尝试使用 JQuery和JSON将值表单视图传递给控制器​​.该查询正在提取网格内的复选框的值.以下是代码

<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",grid.Column("ContactName","Contact Name",grid.Column("Address","Address",canSort: false),grid.Column("City","City",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);
        }
    }

当我单击删除按钮时,值将转到控制器并删除记录.但问题是,在将记录删回到控制器后,我收到以下错误:FireFox的“SyntaxError:JSON.parse:意外字符”,“json解析错误无法识别的标记’<'”用于Safari和“错误” :对象错误.“
搜索各种网站并尝试各种解决方案.但没有任何工作.我正在使用northwind数据库.

提前致谢.

帕塔

解决方法

根据 the docs,以下属性

dataType: "json"

…告诉jQuery你期望从服务器返回的数据类型.然后你的行动就是返回HTML.所以当jQuery尝试解析它所期望的JSON时,它会遇到HTML,并且会给你这个错误.

更改操作以返回JsonResult,或将dataType设置为“html”.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...