locked
Post/Put data from Web API without entity Framework RRS feed

  • Question

  • User-1961814522 posted

    Hi,

    I am new to Web API's. I have a mvc form for getting employee basic details.

    I am trying to submit the form and insert records to database without Entity Framework through Web API.

    Any samples or links to try the functionality will be appreciated.

    Thanks,

    Ashvin

    Saturday, July 15, 2017 7:08 AM

All replies

  • User2119946224 posted

    Hello,

    As per me if you don't want to use EF than use ADO.NET like below link:

    http://www.c-sharpcorner.com/UploadFile/97fc7a/webapi-restful-operations-in-webapi-using-ado-net-objects-a/

    http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-Asp-Net-form-data-into-database-using-web-api/

    Hope it helps you. If yes please mark as answer.

    Regards,

    Saturday, July 15, 2017 12:51 PM
  • User1120430333 posted

    You should discover what the Repository and DAO patterns  are about, with the DAO in the DAL using straight-up ADO.NET  SQL Command objects and custom objects called DTO(s).

    http://blog.sapiensworks.com/post/2012/11/01/Repository-vs-DAO.aspx

    https://www.codeproject.com/Articles/526874/Repositorypluspattern-cplusdoneplusright

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    https://en.wikipedia.org/wiki/Data_transfer_object

    You should understand SoC.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    Saturday, July 15, 2017 1:57 PM
  • Monday, July 17, 2017 6:52 AM
  • User-271186128 posted

    Hi Ashvin,

    I am trying to submit the form and insert records to database without Entity Framework through Web API.

    You could refer to the following sample code to insert/update records using ADO.Net.

    Code in Model:

    public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        }
    

    Code in Api Controller:

    public class ProductsController : ApiController
        {
            public SqlConnection conn = new SqlConnection();
            //POST: /api/products
            public HttpResponseMessage PostProduct([FromBody]Product item)
            {
                conn.ConnectionString = @"database connection string";
                string sqlText = "Insert into products values(@Id,@name,@category,@price)";
                SqlCommand sqlCmd = new SqlCommand(sqlText, conn);
                sqlCmd.Parameters.AddWithValue("@Id", item.Id);
                sqlCmd.Parameters.AddWithValue("@name", item.Name);
                sqlCmd.Parameters.AddWithValue("@category", item.Category);
                sqlCmd.Parameters.AddWithValue("@price", item.Price);
                conn.Open();
                int i = sqlCmd.ExecuteNonQuery();
                conn.Close();
                var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);
                string uri = Url.Link("DefaultApi", new { id = item.Id });
                response.Headers.Location = new Uri(uri);
                return response;
            }
            //PUT: /api/products/id
            public void PutProduct(Product product)
            {
                conn.ConnectionString = @"SQL database connection";          
                string sqlText = "update products set Id=@Id,Name=@name,Category=@category,Price=@price";
                SqlCommand sqlCmd = new SqlCommand(sqlText, conn);
                sqlCmd.Parameters.AddWithValue("@Id", product.Id);
                sqlCmd.Parameters.AddWithValue("@name", product.Name);
                sqlCmd.Parameters.AddWithValue("@category", product.Category);
                sqlCmd.Parameters.AddWithValue("@price", product.Price);
                conn.Open();
                int i = sqlCmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    

    Code in View:

    <h1>My WebAPI</h1>
    <div id="body">
        <section>
            <h2>Add Record</h2>
            Id:<input id="Id" type="text" />
            Name:<input id="name" type="text" /><br />
            Category:<input id="category" type="text" />
            Price:<input id="price" type="text" /><br />
            <input id="addItem" type="button" value="AddRecord" />
        </section>
    
        <section>
            <br />
            <br />
            <h2>Update Record</h2>
            Id:<input id="id2" type="text" /><br />
            Name:<input id="name2" type="text" /><br />
            Category:<input id="category2" type="text" />
            Price:<input id="price2" type="text" /><br />
            <input id="editItem" type="button" value="UpdateRecord" />
        </section>
    
    </div>
    <!--javascript-->
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
            //create a model to save input data
            var Product = {
                create: function () {
                    Id: "";
                    Name: "";
                    Category: "";
                    Price: "";
                    return Product;
                }
            }
            //Add a record. method:POST  url:  /api/Products
            //Request PostProduct(Product item) method in ProductsController
            $("#addItem").click(function () {
                var newProduct = Product.create();
                newProduct.Id = $("#Id").val();
                newProduct.Name = $("#name").val();
                newProduct.Category = $("#category").val();
                newProduct.Price = $("#price").val();
    
                $.ajax({
                    url: "/api/Products",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(newProduct),
                    success: function () {
                        alert("Success!");
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("Request failed,info:" + textStatus + "  " + errorThrown);
                    }
                });
            });
    
            //update a record. method:PUT  url:  /api/Products/Id
            //Request PutProduct(int id, Product product) method in ProductsController
            $("#editItem").click(function () {
                var newProduct = Product.create();
                newProduct.Id = $("#id2").val();
                newProduct.Name = $("#name2").val();
                newProduct.Category = $("#category2").val();
                newProduct.Price = $("#price2").val();
    
                $.ajax({
                    url: "/api/Products/" + $("#id2").val(),
                    type: "PUT",
                    data: JSON.stringify(newProduct),
                    contentType: "application/json; charset=urf-8",
                    success: function () {
                        alert("Success! ");
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("Request failed,info:" + textStatus + "  " + errorThrown);
                    }
                });
            });
    </script>
    

    The output as below:

    Best regards,
    Dillion

    Wednesday, August 2, 2017 5:23 AM