Click here to Skip to main content
15,881,248 members
Articles / Web Development / HTML

A Reusable MVC.NET JQuery Modal Popup

Rate me:
Please Sign up or sign in to vote.
4.33/5 (8 votes)
6 Apr 2016CPOL3 min read 38.8K   2K   14   3
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)


Written By
Web Developer MyMarket
South Africa South Africa
Been developing for about 7 years now. Love solving new and interesting problems. Especially enjoy web GUI projects.

Worked as a web developer for K2 SourceCode. Projects worked on: K2 WorkSpace, BlackPoint, BlackPearl and K2 for SharePoint.

Currently working at BidTravel and helping them out with their Procurement systems.

Living in sunny South Africa.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1447367217-Oct-19 16:46
Member 1447367217-Oct-19 16:46 
QuestionWould you please provide the .mdf or related SQL script ? Pin
jasper1688821-May-19 21:09
jasper1688821-May-19 21:09 
QuestionRe-usable modal Pin
Member 1363005721-Feb-18 8:54
Member 1363005721-Feb-18 8:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.