samedi 3 septembre 2016

Passing a JSON object to a controller

I'm new to MVC and JavaScript, and while this may be an obvious answer for some I've been struggling for a while now (after looking at many examples)!

When debugging through the Index.cshtml view, the newData object hasn't been populated by the textboxes (set up in a partial view called AddNewProduct.cshtml). The partial view is displayed by clicking a button set within Index.cshtml (this works fine). I can see that the newProduct object in my controller has not been filled due to the problem in the view.

My main question is how do I get the values from my textboxes into the newData object?

Any suggestions would be greatly appreciated! Thank you.

HomeController.cs:

[HttpPost]
        public PartialViewResult RunAddNewProduct(Product newProduct)
        {
                SqlConnection con = new SqlConnection();
                con.ConnectionString = Connections.connection;
                con.Open();

                using (con)
                {
                    SqlCommand cmd = new SqlCommand("INSERT INTO Product VALUES(@Id, @Name, @Description, @Price, @UnitsInStock)", con);

                    cmd.Parameters.Add(new SqlParameter("@Id", newProduct.Id));
                    cmd.Parameters.Add(new SqlParameter("@Name", newProduct.Name));
                    cmd.Parameters.Add(new SqlParameter("@Description", newProduct.Description));
                    cmd.Parameters.Add(new SqlParameter("@Price", newProduct.Price));
                    cmd.Parameters.Add(new SqlParameter("@UnitsInStock", newProduct.UnitsInStock));

                    SqlDataReader rd = cmd.ExecuteReader();

                    while (rd.Read())
                    {
                        newProduct.Id = Convert.ToInt32(rd.GetInt32(0));
                        newProduct.Name = Convert.ToString(rd.GetSqlValue(1));
                        newProduct.Description = Convert.ToString(rd.GetSqlValue(2));
                        newProduct.Price = Convert.ToDecimal(rd.GetDecimal(3));
                        newProduct.UnitsInStock = Convert.ToInt32(rd.GetInt32(4));
                    }
                }
                return PartialView("AddNewProduct", newProduct);           
        } 

Index.cshtml:

$('#btnConfirmNewProduct').live('click', function () {

        var newData = {
                'id': $('#txtId').val(),
                'name': $('#txtName').val(),
                'description': $('#txtDesc').val(),
                'price': $('#txtPrice').val(),
                'unitsInStock': $('#txtUnitsInStock').val()
        };

        $.ajax({
            url: '/Home/RunAddNewProduct',
            data: JSON.stringify(newData),
            type: 'POST',
            dataType: 'json'
        })
            .success(function (result) {
                $('#products').html(result);
            })
            .error(function (xhr, status) {
                alert(status);
            })
    });

AddNewProduct.cshtml:

<table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th>Units In Stock</th>
        </tr>
        <tr>
            <td><input id="txtAddId" type="text"/></td>
            <td><input id="txtAddName" type="text"/></td>
            <td><input id="txtAddDesc" type="text"/></td>
            <td><input id="txtAddPrice" type="text"/></td>
            <td><input id="txtAddUnitsOfStock" type="text"/></td>
        </tr>
    </table>
    <input id="btnConfirmNewProduct" type="button" value="Confirm New Product" />

Aucun commentaire:

Enregistrer un commentaire