5

I am working on MVC4 and trying to pass values form view to controller using JQuery and JSON. The query is extracting values of checkboxes inside a grid. Following is the code:

<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);
            }
        });
    }
}

My html code is following:

<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>
        )
})

When I click on delete button the jquery mentioned above will take the selected values to the controller. The controller code is written below:

[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);
        }
    }

When I click on the delete button, the values go to controller and delete records. But the problem is, after deleting records when it back to controller, I am getting the following error: "SyntaxError: JSON.parse: unexpected character" for FireFox, "json parse error unrecognized token '< '" for Safari and "Error: object error." I search various sites and try various solutions. But nothing is working. I am using Northwind db.

Thanks in advance.

Partha

3 Answers 3

13

According to the docs, the following property:

dataType: "json"

... tells jQuery the type of data you're expecting back from the server. Then your action is returning HTML. So when jQuery tries parsing the JSON it's expecting, it runs into HTML, and gives you this error.

Either change the action to return a JsonResult, or set your dataType to "html".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks StriplingWarrior. Your suggestion is working. It is deleting selected data without any error. But problem is when it back to the index page the deleted data remains there with checked mark until I refresh the page. Do you have any clue. Thanks again.
@Partha: Yes. You are using an AJAX call, and the invoked action is returning a view, but your AJAX callback is doing nothing with the returned data. Typically, if you expect the entire view to be rendered by the browser, you may want to do a non-ajax post (stackoverflow.com/a/5524053/120955). Otherwise, figure out how you want to make your success callback modify the page with the new information, either by changing the checkbox value directly, or by returning a partial view from the controller action and replacing a portion of the page with the returned HTML.
0

Not sure, but I did notice you're not passing JSON in your $.ajax call... Try:

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

JSON uses double quotes around the member names.

Comments

0

After two day of searching, testing and debugging for a solution to this crazy error, I found that the problem was the jquery library. I was starting a new project so I choose the recent jquery-1.10.2.js, and got the error. Tried jquery-1.9.1.js, and also got the error. But when I tested with jquery-1.5.2.js, the success function worked fine and no error was throw.

2 Comments

But what about the latest version?
I don't right recall, however for some reason I found that jquery-1.10.2.js was the latest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.