Update page without loading it using PartialView


How can I make a controller in ASP.NET MVC do something(here it is inserting data in database) but doesn't load or reload the whole view just the partial view

MVC-Controller

In the view, i have got a button which will insert data into the database, and return the updated data.

 


Asked by:- vikas_jk
1
: 5930 At:- 6/7/2017 11:20:39 AM
C# MVC ASP.NET







1 Answers
profileImage Answered by:- jaiprakash

I have done similar work in past, you can do same but replace your mode and it's data according to your data.

Note:
I am using Customer class data , please replace model and it's column with your data.

Step  1 : Create a Method in Controller to return model list and partial view to show it

//Method to return Partial View
        public ActionResult Table()
        {
            var ModelList = new List<Customer>();

            using (var context = new NorthWindEntities())
            {
                ModelList = (from s in context.Customers
                             select s).ToList();


            }
            return PartialView(ModelList);
        }

Step 2 : Create table in partial view

@model IEnumerable<Test.Models.Customer>

<table class="table table-condensed">
    <thead>
        <tr>
            <th>Customer Name</th>

            <th>Work Area</th>
            <th>City</th>
        </tr>
    </thead>
    <tbody>
        <!--Loop through each customer to show it's data-->
        @foreach (var Customer in Model)
        {
            <tr>
                <td>@Customer.Customername</td>
                <td>@Customer.WorkArea</td>
                <td>@Customer.City</td>
            </tr>
        }

    </tbody>
</table>

Step 3: Load the form fields to add new customer and table using the above created partial view, so in controller C# code will be

        public ActionResult GetCustomer()
        {

            return View();
        }

And view for it, will be

<!--Form To add new customer-->
<div class="form-group">
    <div class="row">
        <div class="col-lg-2">
            Customer Name
        </div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.Customername, new { @class = "form-control" })
        </div>
    </div>
</div>
<div class="form-group">
    <div class="row">
        <div class="col-lg-2">
            Work Area
        </div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.WorkArea, new { @class = "form-control" })
        </div>
    </div>
</div>
<div class="form-group">
    <div class="row">
        <div class="col-lg-2">
            City
        </div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.City, new { @class = "form-control" })
        </div>
    </div>
</div>
<input type="button" class="btn btn-primary" id="AddNewCustomer" value="Add New Customer" />

<!--Div to show table Data-->
<div id="TableData">


</div>

In the above view , we have added input fields to add new customer and a div to load table data in it.

Now Important step, load this script in above view, to load table using the ajax call and send new customer data using ajax

<script>
    $(document).ready(function () {


    //Get Table data on page load
        $.ajax({
            url: '/home/Table', //url to load table data
            type: 'GET',
            success: function (result) {
                //Get result data in html and append it in the div
                $("#TableData").html(result);
            },
            error: function () {
                //Show error here
                alert("Error");
            }

        })


        //Submit Data on Click
        $("#AddNewCustomer").on('click', function () {
            //do validation here for data if needed.

            var customers = []; //create empty array for all customer
            var customer = []; //create array for customer data
            
            //this should exactly match the columns of your table
            customer = {
                Customername: $("#Customername").val(),
                WorkArea: $("#WorkArea").val(),
                City: $("#City").val(),
                ContactTitle: null,
                Address:null



            }

            //push created customer in Customer array
            customers.push(customer);

            //Post data to C# controller
            $.post('/Home/AddNewCustomer',
                {
                    StringData: JSON.stringify(customers) //Send data as string data
                },
                function (data) {
                    //if there was no error, get updated data
                    if(data==true)
                    {
                        //Get Updated data from table
                        $.ajax({
                            url: '/home/Table', //url to load table data
                            type: 'GET',
                            success: function (result) {
                                //replace it with new data
                                $("#TableData").html(result);
                            },
                            error: function () {
                                //Show error here
                                alert("Error");
                            }

                        })
                    }
                }
            );

        })

    });
</script>

I have exaplined script with comments, now the last part C# code to save data in database.

        [HttpPost]
        public JsonResult AddNewCustomer(string StringData)
        {
          //Deserialize it 
            List<Customer> Customers = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Customer>>(StringData);
            try
            {
                using (var context = new NorthWindEntities())
                {
                    //loop through customer
                    foreach (var Customer in Customers)
                    {
                        context.Customers.Add(Customer);
                      
                    }
                    context.SaveChanges();
                }
                return Json(true);   
            }
            catch (Exception e)
            {
                return Json(false);
            }
           
        }

we are posting data to controller as JSON string and then converting it into class using JavaScriptSerializer()

That's it, we are done, you can deseriliaze a single object instead of list also.
Hopefully it will help, it was working in my project.

 

1
At:- 6/7/2017 12:29:28 PM Updated at:- 11/17/2022 7:50:27 AM
Thank you for quick answer 0
By : vikas_jk - at :- 6/7/2017 12:42:41 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use