Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

A Reusable MVC.NET JQuery Modal Popup

4.33/5 (8 votes)
6 Apr 2016CPOL3 min read 39.7K   2K  
A reusable jQuery popup message box with Ajax functionality - that can bind to any model

Image 1

Introduction

Displays a reusable jQuery modal pop-up. The jQuery modal pop-up's content section can be dynamically bound to any data model of your choice. Thus, the modal allows the developer to "inject" HTML content via a number of useful techniques.

Background

You will need a good understanding of jQuery, MVC and C# code.

Simple Example: Using the Code

It is really easy to use the control:

  1. Ensure to add the helper control onto your page.
  2. Ensure to assign all the necessary properties.
  3. Add an additional HTML you would like to see displayed within the modal content section:
JavaScript
  @using (Html.BeginPopupModal(new PopupModel("messageDialog") {
    Title = "Hi there",
    TitleImageUrl = "~/Images/User_Male_Check.png",
    PopupButtonSet = PopupButtonSet.OkPostbackClose,
    ClientFunction = "SavePerson()" }))
{
    // all the Person Model data will be bound within into this Content section
    @Html.Partial("_Person");
}

Set up your modal pop-up control's properties:

JavaScript
// Set up what values you want in your pop-up modal control.
Title = "Hi there",
TitleImageUrl = "~/Images/User_Male_Check.png",
PopupButtonSet = PopupButtonSet.OkPostbackClose,
ClientFunction = "SavePerson()"

When the "OK" button is clicked on - within the Modal pop-up control, you can decide what to do after the event has fired. In my example: The "SavePerson()" client side function will be executed. Within this function, one could decide whether you want to call a Web API or a Controller method.

The modal windows content is wrapped inside of a hidden DIV - you are fee to place whatever content (HTML) is relevant to your modal pop-up. It is up to the developer to decide what will happen after the "OK" button has been clicked inside of the modal pop-up. Therefore, you can decide to change the message of the modal pop-up as I did below. Or you can redirect to another page if desired.

Client Side Function Call

JavaScript
// Here is the client side function. In this example once the "ok" button is clicked
// I take the values from the modal 'page' and do a GET to a
// Controller Method named: "/Home/SavePerson"

function SavePerson() {
    var name = $("#txtName").val();
    var address = $("txtAddress").val();
    var data = JSON.stringify({ Name: name, Address: address });

    //lets make a Ajax call to the Controller Method
     $.ajax({
        url: "/Home/SavePerson?JSONString=" + data,
        datatype: "application/json",
        type: "GET",
        success: function (data) {
            $('.messageDialog-content').html(data);
        },
        error: function (e) {
            $(".messageDialog-content").html("ERROR");
        }
    });}

Server Side Controller Method Call

JavaScript
// Here the controller method is called.
// The developers can decide what to do with the incoming parameters.

public ActionResult SavePerson(string JSONString)
{
    using (Stream jsonSource = Utilities.StringToStream(JSONString))
    {
        // serializer will read data stream
        var s = new DataContractJsonSerializer(typeof(Person));
        var person = (Person)s.ReadObject(jsonSource);
        return Content("Well done " + person.Name + ". You clicked on the OK button");
    }
}

Extended Example

I have also included a more 'complex' example - or a slightly more real world example. In this example, I show how the pop-up can be used in conjunction with a Grid or List of items. This example can be found here: "/People/Index".

In this example, you can see that I have added the modal popup control just under the foreach loop.

JavaScript
@foreach (var item in Model)
    {
        < tr>
            < td>
                @Html.DisplayFor(modelItem => item.Value.Name)
            < /td>
            < td>
                @Html.DisplayFor(modelItem => item.Value.LastName)
            < /td>
            < td>
                @Html.DisplayFor(modelItem => item.Value.Address)
            < /td>
            < td>
                < a href="#" data-id="@item.Key" class="my-edit">Edit< /a>
            < /td>
        < /tr>
    }

In order to update the necessary row, one has to keep track of which record "key" one would like to display for the update. One does this by ensuring that the a key value is added as an "data-id" attribute within the "edit" hyperlink.

JavaScript
<a href="#" <b>data-id="@item.Key"</b> class="my-edit">Edit< /a>

Now that we know exactly what row item we are attempting to edit - We can make a call to the server to pull the details of that particular object into the pop-up modal for us.

Note: Instead of just returning a simple JSON object - I thought it would be great to pull through an actual View ("_Person.cshtml" in this instance) which would translate into a partial HTML snippet. In this way - we don't need to worry about populating any fields/inputs on the client side as most of this work will be done for us once the model has been bound to the view. 

JavaScript
public ActionResult GetPerson(string idx)
{
    Person person;
    if (people.TryGetValue(int.Parse(idx), out person))
    {

       return PartialView("~/Views/Home/_Person.cshtml", person);

       //you could also pass a JSON object of the Person Model - if you so wished
       //you have to "AllowGet" to pass the security restriction
       //return Json(person, JsonRequestBehavior.AllowGet);
     }
     else
        return null;
}

We now have the ability to update any one of the properties for this Person object.

Again: you will notice that one of my parameters is of type "Person" - thus simplifying the task of the actual update process.

JavaScript
[HttpPost]
public ActionResult Edit(int id, Person person)
{
   Person found;
   int key = int.Parse(id.ToString());
   if (people.TryGetValue(key, out found))
   {
       found.Name = person.Name;
       found.Address = person.Address;
       found.LastName = person.LastName;

       return Content("Well done. " + found.Name + " - has now been updated!");
    }
    else
    {
       return Content("Nope! Something went wrong.");
    }        
}

That's it. We have successfully updated an item in the collection.

Please feel free to download the source code at the top of the page.

Enjoy! 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)