Skip to main content

MVC 3 Reload PartialView by using jQuery and AJAX

Sometimes it`s easier to reaload only part of the website witout reloading whole page. Thanks to AJAX technology such aproach is possible and easy to code. Let`s begin.

Firstly we need to configure our environment so we must have a Visual Studio with MVC 3  Razor isntalled on it. Razor can be obtained from here. After installation process completed , the second step is to set up a new WebStie project (Picture 1.)

Picture 1.
After you confirm Your project type choise, next window starts. On it You should select the second web project type (with Forms autentication method)  and than choose RAZOR form dropdown (Picture 2.).
Picture 2.
Now You new web solution contains several folders and files by default. Their description is not a point of this article so allow myself to continue. Next step is to create a simple model for our PartialView. As an example I  created a simple _UserModel.cs in Models folder. The source code for this model is:


 public class _UserModel
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Surname { get; set; }
    }
The "[Required]" attribute gives an information for MVC  engine to auto-validate the data is not empty. This model is really simple, don`t You think?

Now when we have our simple model, it`s time to create a simple PartialView for them. Let`s our simple user partial view has a name _User (the names starts with "_" means that the model or view is for parialand be located in Views/Home directory (Picture 3.)
Picture 3.
The content of out partial present below


@model ReloadPartial.Models._UserModel
     
@using (Html.BeginForm("PostMyForm","Home", FormMethod.Post, new { id = "myForm" }))
{
    <h3>
        @Html.ValidationSummary()
    </h3>

    @Html.Raw("Name:")
    @Html.TextBoxFor(m => m.Name)
    <br />
    @Html.Raw("Surname:")
    @Html.TextBoxFor(m => m.Surname)
    <br />
    <input type="button" value="!!Action!!" onclick="SubmitForm();" />
}

After view completed lets focus on controller method. Because we add our view to the Home dictionary out controller is Controllers/HomeController.cs by deafult. In controller code we need to add one simple function which returns PartialViewResult and as a argument take a _UserModel object.


 public PartialViewResult PostMyForm(_UserModel model)
        {
            ModelState.Clear(); //important to see changes in UI
            if (ModelState.IsValid)
            {
                //TODO:  something with model data
            }
            return PartialView("_User",model);
        }
Really simple code...

The last thing  to to is to render our partial. The simplest way to do that is to embed it into Index view which is located in Views/Home. To render our partial we use:
@{Html.RenderPartial("_User", new ReloadPartial.Models._UserModel());}

But is not finish yet, we must make a postback by using jQuery and AJAX. The jQuery framework was added to the project by default in the Views/Shared/_Layout view so we can simple use it.


<script language="javascript" type="text/javascript">

    function SubmitForm() {
        //select and serialize our small form
        var frm = $("#myForm").serialize();
       // get form action
        var action = $("#myForm").attr("action");
        $.ajax({
            url: action,  // or  '@(Url.Action("PostMyForm"))',
            cache: false,
            async: true,
            type: "POST",
            data: frm, //data to post to server
            error: function (html) { alert(html); }, //something goes wrong...
            success: function (data) {
                $("#myForm").html(data); //replace our form content
            }
        });
    }
</script>

It`s done and work:)

Have a fun

Read more..


Popular posts from this blog

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileStream

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition

Using Newtonsoft serializer in CosmosDB client

Problem In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB.  Solution In CosmosDBV3 .NET Core API, when creating an instance of  CosmosClient one of optional setting in  CosmosClientOptions is to specify an instance of a Serializer . This serializer must be JSON based and be of  CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from  CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex.  For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from  CosmosSerializer.  using  Microsoft.Azure.Cosmos; using  Newtonsoft.Json; using  System.IO; using  System.Text; ///   <