Monday, July 8, 2013

How to insert data into table in MVC

After filling the form and click the submit, definately  the the form will post some data
View: fillcustomer1.aspx
<body>
    <% using (Html.BeginForm("FillCustomer1", "Customer", FormMethod.Post))
       {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Code) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Code) %>
                <%: Html.ValidationMessageFor(model => model.Code) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CustomerName) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CustomerName) %>
                <%: Html.ValidationMessageFor(model => model.CustomerName) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Salary) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Salary) %>
                <%: Html.ValidationMessageFor(model => model.Salary) %>
            </div>
         
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Viewlist","Customer")%>
    </div>
</body>

Now we have to insert the data into database:

Controller: Customer: in the below code CustomerEntities1  is nothing but our database(.emdx) file

        [Authorize] //Here we are just designing our action with authorize for form authentications
        [HttpPost]
        public ActionResult FillCustomer1(tb_EmpDetails emp_details)
        {
            //here we are using the .edmx(copy of database) file.....
            using (CustomerEntities1 customerdetails = new CustomerEntities1())
            {
                if (ModelState.IsValid)
                {
                    //here we are passing(adding) the  values to table using addtotable
                    customerdetails.AddTotb_EmpDetails(emp_details);
                    //after adding the values to table save the table
                    customerdetails.SaveChanges();
                    //redirecting from one action to another action
                    return RedirectToAction("Viewlist", "Customer");
                }
                else
                {
                    ModelState.AddModelError("", "Please enter fields properly");
                    //Content("<script language='javascript' type='text/javascript'>alert('Please enter fields properly');</script>");
                    return View();                      
                }
            }

        }


No comments:

Post a Comment