Click here to Skip to main content
11,642,855 members (71,161 online)
Click here to Skip to main content

ASP.NET MVC 5 List Editor with Bootstrap Modals

, 24 Feb 2015 CPOL 59.5K 5.8K 83
Rate this:
Please Sign up or sign in to vote.
With this sample I'll try to demonstrate how to achieve editing of One-To-Many model in the single View.

Introduction

The idea is to display standard Edit View with standard scaffolded editors for the master object and augment it with the list of editors allowing to edit list of child objects on same page.

Background

Normally what we get out of the box from VS2013 Asp.Net MVC template and scaffoldings concerns simple models. After creating few projects I decided to create an invoice sample.
Immediately I found out that it is not so simply task until I've discovered the magic RenderAction Http extension. I've tried to keep attached example very simple to follow but the basic knowledge of Asp.Net MVC is required.

The code

At first let's create the standard new Asp.Net project called TestAjax by selecting MVC template with core references set to MVC and without Authentication.

To keep it simple let's create two models: Person and a list of Addresses assigned to each Person.

In the Models folder add two classes:

namespace TestAjax.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Display(Name = "First Name")]
        [Required]
        [StringLength(255, MinimumLength = 3)]
        public string Name { get; set; }

        [Display(Name = "Last Name")]
        [Required]
        [StringLength(255, MinimumLength = 3)]
        public string  Surname { get; set; }

        public virtual ICollection<Address> Addresses { get; set; }
    }
}

 

namespace TestAjax.Models
{
    public class Address
    {
        public int Id { get; set; }

        [Required]
        [StringLength(255, MinimumLength = 3)]
        public string City { get; set; }
       
        [Display(Name = "Street Address")]
        public string Street { get; set; }

        [Phone]
        public string Phone { get; set; }

        public int PersonID { get; set; }
        public virtual Person Person  { get; set; }
    }
}

Now, as we have our models in place let's create controllers. Right clicking Controllers folder select the Add, Controller... menu, and from the dialog select "MVC 5 Controller with views, using Entity Framework". Let's select Person as a model class, create new DataDb context and have all checkboxes set in the dialog. Rebuild the project and add another controller for Address selecting the already created DataDb context.

To end preparation stage remove HomeController and Home folder from Views. In the shared _Layout View let's replace standard menu items for Home, About, Contact with the one that points to People: @Html.ActionLink("People", "Index", "People"), and finally in App_Start\RouteConfig.cs we must replace the word Home with People so our app will point to People controller by default.

Now, as we have our project up and running we will modify the presentation.

Bootstrap icons in buttons

To prettify buttons in the sample I've decided to decorate them with bootstrap glyphicons.

Because of glyphicons syntax:

<button type="button" class="btn btn-default btn-lg">
  <span class="glyphicon glyphicon-star"></span> Star
</button>

I've added additional helper to achieve correct html output from ActionLink helper.

In the project let's create Helpers folder and inside of that the MyHelper.cs class.

Helper code:

// As the text the: "<span class='glyphicon glyphicon-plus'></span>" can be entered
        public static MvcHtmlString NoEncodeActionLink(this HtmlHelper htmlHelper,
                                             string text, string title, string action,
                                             string controller,
                                             object routeValues = null,
                                             object htmlAttributes = null)
        {
            UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            TagBuilder  builder = new TagBuilder("a");
            builder.InnerHtml = text;
            builder.Attributes["title"] = title;
            builder.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
            builder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));

            return MvcHtmlString.Create(builder.ToString());
        }

So, now to output glyphed button using ActionLink I can use this syntax:

@Html.NoEncodeActionLink("<span class='glyphicon glyphicon-plus'></span>", "Add new Person", "Create", "People", routeValues: null, htmlAttributes: new { @class = "btn btn-primary" })

In the Index View of People Controller let's add the @using TestAjax.Helpers directive at the top of the page. After that let's replace the @Html.ActionLink("Create New", "Create") with

<div class="pull-right">
 @Html.NoEncodeActionLink("<span class='glyphicon glyphicon-plus'></span>", "Add new Person", "Create", "People", routeValues: null, htmlAttributes: new { @class = "btn btn-primary" })
</div>

and Edit, Details, Create ActionLinks with

<div class="pull-right">
    @Html.NoEncodeActionLink("<span class='glyphicon glyphicon-pencil'></span>", "Edit", "Edit", "People", routeValues: new { id = item.Id }, htmlAttributes: new { data_modal = "", @class = "btn btn-default" })
    &nbsp;
    @Html.NoEncodeActionLink("<span class='glyphicon glyphicon-search'></span>", "Details", "Details", "People", routeValues: new { id = item.Id }, htmlAttributes: new { data_modal = "", @class = "btn btn-default" })
    &nbsp;
    @Html.NoEncodeActionLink("<span class='glyphicon glyphicon-trash'></span>", "Delete", "Delete", "People", routeValues: new { id = item.Id }, htmlAttributes: new { data_modal = "", @class = "btn btn-danger" })
</div>

Now we should have our icons in place.

The list

To develop list of addresses in the Person Edit View I will try to implement the following idea:

The Html.RenderAction will inject output from different action to the view. The only thing we must remember is that the child controller must not allow to "escape" from the view. For this reason we will implement all of the child Views as Partials edited in-place with Modals.

To start, edit the Edit View of People Controller. Just before the "Back to list" div let's add the following part:

<div class="row">
    <div class="col-md-offset-2 col-md-10">
        @{ Html.RenderAction("Index", "Addresses", new { id = Model.Id }); }
    </div>
</div>

Now we must modify the Addresses Controller because it returns the standard View in the Index Action , what we need is the PartialView instead. So I've tried to enter this kind of code for the Index Action:

// GET: Addresses
[ChildActionOnly]
public async Task<ActionResult> Index(int id)
{
    ViewBag.PersonID = id;
    var addresses = db.Addresses.Where(a => a.PersonID == id);

    return PartialView("_Index", await addresses.ToListAsync());
}

After startup I received the error "HttpServerUtility. Execute was blocked by waiting for the end of an asynchronous operation." After little investigation in internet I found out that asynchronous operations are still not allowed in child actions in this version of MVC. So as a quick fix let's delete Addresses Controller and Addresses Folder in Views, after that let's rescaffold the Addresses Controller again but with "Use async controller actions" unchecked this time. The edited Index action now should look like:

[ChildActionOnly]
public ActionResult Index(int id)
{
    ViewBag.PersonID = id;
    var addresses = db.Addresses.Where(a => a.PersonID == id);

    return PartialView("_Index", addresses.ToList());
}

Then we have to rename the "Index.cshtml" to "_Index.cshtml" in the Views\Addresses and we can give it a run. I've decorated the Index action with the [ChildActionOnly] attribute because we don't want this method to be called directly. The id parameter allows us to retrieve addresses for the given person. The ViewBag.PersonID will be useful to call Create Address in the Index later on.

The program is now running but we did not implemented the in-place editing of addresses yet so clicking in Create link would take us to another view - you can try that by removing temporally the [ChildActionOnly] attribute and clicking that link. To avoid escaping from the View we will use Bootstrap Modals with some help of javaScript.

Bootstrap Modals

I'm not a javaScript wiz but somehow I've developed the following script to display bootstrap modals:

// modalform.js

$(function () {

    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {

        // hide dropdown if any
        $(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');

       
        $('#myModalContent').load(this.href, function () {
           

            $('#myModal').modal({
                /*backdrop: 'static',*/
                keyboard: true
            }, 'show');

            bindForm(this);
        });

        return false;
    });

});

function bindForm(dialog) {
   
    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    //Refresh
                    location.reload();
                } else {
                    $('#myModalContent').html(result);
                    bindForm(dialog);
                }
            }
        });
        return false;
    });
}

The script to function requires three things:

1. In the view this sort of placeholder:

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

2. In the view that we want to place in the modal this kind of markup:

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Add new Address</h4>
</div>

@using (Html.BeginForm())
{
    <div class="modal-body">
        // Place Form  editors here
    </div>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Cancel</button>
        <input class="btn btn-primary" type="submit" value="Add" />
    </div>
}

3. The action supporting View in the modal must return Json(new { success = true }); instead of the View();

Notice: Please note that script needs the data-modal attribute in invoking ActionLink

Notice: It is good to add type="button" attribute to the data-dismiss button - you will avoid problems with Bootstrap Modal when user presses Return key to accept dialog - in some browsers Modal without this attribute is just closed.

For more complete Bootstrap 3.1.1 Modals in MVC 5 focused sample please visit this site.


In our project I've added the modalform.js to the \Sripts folder and the

bundles.Add(new ScriptBundle("~/bundles/modalform").Include("~/Scripts/modalform.js"));

line to the AppStart\BundleConfig.cs.

Now edit the "_Index.schtml" to have this layout:

@using TestAjax.Helpers
@model IEnumerable<TestAjax.Models.Address>

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>

Add support for modals in the "Edit.cshtml" of People in the scripts section:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/modalform")
}

To work with Modals in the Addresses Controller we must also modify the Create methods:

public ActionResult Create(int PersonID)
{
    Address address = new Address();
    address.PersonID = PersonID;

    return PartialView("_Create", address);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,City,Street,Phone,PersonID")] Address address)
{
    if (ModelState.IsValid)
    {
        db.Addresses.Add(address);
        db.SaveChanges();
        return Json(new { success = true });
    }

    return PartialView("_Create");
}

And finally the renamed "_Create.cshtml" of Addresses should have this shape:

@model TestAjax.Models.Address

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

Now we can add new Address line without escaping from the Person Edit View.

Same pattern should be followed to create _Edit and _Delete Partials.

Additionaly we can create a _List Partial to be displayed in the Details View of Person.

For the rest of the Partials please refer to the attached download which contains full source for the project.

Notice: Rebuild project to update Nuget packages in the attachment. You should have both "Allow Nuget to download missing packages" and "Automatically check for missing packages during build in Visual Studio" options checked in NuGet settings.

The Problem

There is one deficiency with proposed solution:

The People Edit View gets refreshed each time the Address is added, changed or deleted.

The Solution

The solution of above glitch is to Ajaxify the thing.

Full page refresh comes from this line in my script:

location.reload();

To fix it, we must prepare a new version:

// modalform.js

$(function () {
    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {
        // hide dropdown if any (this is used wehen invoking modal from link in bootstrap dropdown )
        //$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');

        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                /*backdrop: 'static',*/
                keyboard: true
            }, 'show');
            bindForm(this);
        });
        return false;
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#replacetarget').load(result.url); //  Load data from the server and place the returned HTML into the matched element
                } else {
                    $('#myModalContent').html(result);
                    bindForm(dialog);
                }
            }
        });
        return false;
    });
}

 

As you can see, now we are replacing the content of DOM element with id="replacetarget" using url received as JSON from the Action.

Some refactoring in our project will be required for script to function properly.

First, let's move the @Scripts.Render("~/bundles/jquery") line in Shared\_Layout.cshtml to the <head> area at the top of the page. The reason for that is we will need access to jQuery earlier then before.

Now, in the Edit View of People Controller let's modify the part after the ending bracket of the form:

} // End of @using (Html.BeginForm())

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>

As you see we have moved the modal placeholder here (removed from the _Index partial) because we do not want this part to be replaced with the script. Just before Html.RenderAction I've added id="replacetarget" to the div. This is the div to be replaced by the script. Script section now contains only validation.

In the _Index Partial remove the modal block as mentioned above and add @Scripts.Render("~/bundles/modalform") at the end of page add content of the modalform.js in the <script></script> tags (as @Script.Render will not work in Partial). This is why we need jQuery so early. The modalform script is placed here because all of the <div> content will be replaced by javaScript code, so we need to recreate it at each time this happens.

The last thing that we must provide is the result.url JSON data used in our script.

Dig into Addresses Controller code and replace each:

return Json(new { success = true});

line with:

string url = Url.Action("Index", "Addresses", new { id = address.PersonID });

return Json(new { success = true, url = url });

We are using the the Url.Action helper here to build the correct url with the  PersonID that we are currently editing.

And finally remove the [ChildActionOnly] attribute from Index method since it will be called by script, not only by RenderAction in Edit View of Person.

As before the code is available for download above.

Points of Interest

From downloads you can learn:

  • How to deal with in-place dynamic lists in View.
  • How to display Forms in Bootstrap Modals.
  • How to decorate Bootstrap buttons with glyph icons.
  • How to highlight Bootstrap active navbar menu item
  • How to use Ajax to refresh only part of the page

History

2015-02-15 Added two minor fixes:

Problem: Modal dialog sometimes is not modal anymore. Thanks agpulidoc for solution below in comments.

Fix: Partials does not support @script regions - replace with script directly or introduce extensions

Problem: Submit Save Person not working when validation reported error on modal - spotted below in comments

Fix: In modal script when !result.success - bindForm(dialog); should be called instead of bindForm();

2014-01-17 Ajax part added

2014-01-15 Revised

2014-01-14 First version

License

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

Share

About the Author

Jarosław Zwierz
Software Developer Fabro sp.j., Royal Bank of Scotland - Ulster Bank
Poland Poland
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questionvalidation in form and how to use it in mvc5 asp net??? Pin
GREG_DORIANcod31-Jul-15 3:53
memberGREG_DORIANcod31-Jul-15 3:53 
QuestionThanks! Pin
Jervy Valencia19-Jun-15 0:12
memberJervy Valencia19-Jun-15 0:12 
Questionproblem after reload with url Pin
sunn78913-Jun-15 20:20
membersunn78913-Jun-15 20:20 
QuestionModals are not showing as a popup instead they open on another page and as a basic page Pin
Mikail153-Jun-15 22:22
memberMikail153-Jun-15 22:22 
AnswerMessage Removed Pin
Member 1169109328-Jul-15 17:49
memberMember 1169109328-Jul-15 17:49 
GeneralRe: Modals are not showing as a popup instead they open on another page and as a basic page Pin
Member 1169109329-Jul-15 2:53
memberMember 1169109329-Jul-15 2:53 
QuestionUsing this sample I am trying to upload a file with no success. Please help Pin
martintr3-Jun-15 20:31
membermartintr3-Jun-15 20:31 
AnswerRe: Using this sample I am trying to upload a file with no success. Please help Pin
Member 1169109320-Jul-15 9:02
memberMember 1169109320-Jul-15 9:02 
QuestionHow do I control the IDs and names of the added elements? Pin
Shimmy Weitzhandler28-Mar-15 16:14
memberShimmy Weitzhandler28-Mar-15 16:14 
Questionchange to Ajax link Pin
sunn78922-Mar-15 7:48
membersunn78922-Mar-15 7:48 
GeneralMy vote of 5 Pin
Oliver Kohl D.Sc.25-Feb-15 5:07
memberOliver Kohl D.Sc.25-Feb-15 5:07 
GeneralMy vote of 5 Pin
Member 108534569-Feb-15 4:17
memberMember 108534569-Feb-15 4:17 
QuestionSubmit Save Person no working! Pin
Member 37317975-Feb-15 12:18
memberMember 37317975-Feb-15 12:18 
AnswerRe: Submit Save Person no working! Pin
Jarosław Zwierz23-Feb-15 10:39
memberJarosław Zwierz23-Feb-15 10:39 
QuestionWhat is the approach for implementing this MasterDetails within the Create View? Pin
Member 105393245-Jan-15 6:05
memberMember 105393245-Jan-15 6:05 
QuestionClient side validation is not firing for ModalPoup, Pin
Ramanji43417-Nov-14 19:32
memberRamanji43417-Nov-14 19:32 
QuestionNice! Cool article! Pin
Jeonghan K1-Nov-14 0:07
memberJeonghan K1-Nov-14 0:07 
QuestionNot Modal After search Pin
sunn78927-Oct-14 7:14
membersunn78927-Oct-14 7:14 
QuestionGreat post! Pin
RichardJLewis20-Sep-14 21:57
memberRichardJLewis20-Sep-14 21:57 
GeneralMy vote of 3 Pin
DrikaMSouza9-Sep-14 4:29
memberDrikaMSouza9-Sep-14 4:29 
QuestionAdd Second Address not modal Pin
agpulidoc31-Jul-14 11:24
memberagpulidoc31-Jul-14 11:24 
AnswerRe: Add Second Address not modal Pin
Jarosław Zwierz31-Jul-14 23:08
memberJarosław Zwierz31-Jul-14 23:08 
GeneralRe: Add Second Address not modal Pin
agpulidoc11-Aug-14 9:43
memberagpulidoc11-Aug-14 9:43 
GeneralRe: Add Second Address not modal Pin
Joopa21-Jan-15 18:24
memberJoopa21-Jan-15 18:24 
AnswerRe: Add Second Address not modal Pin
Krupskaia Angulo5-Aug-14 14:01
memberKrupskaia Angulo5-Aug-14 14:01 
AnswerRe: Add Second Address not modal Pin
ChrisMVC22-Aug-14 4:31
memberChrisMVC22-Aug-14 4:31 
AnswerSOLVED Pin
agpulidoc23-Sep-14 12:05
memberagpulidoc23-Sep-14 12:05 
GeneralRe: SOLVED Pin
Jarosław Zwierz23-Feb-15 10:42
memberJarosław Zwierz23-Feb-15 10:42 
AnswerSolved -- extra attributes needed in the launch modal button Pin
Zijian13-Jan-15 19:48
memberZijian13-Jan-15 19:48 
QuestionObject on Create Pin
agpulidoc31-Jul-14 10:54
memberagpulidoc31-Jul-14 10:54 
AnswerRe: Object on Create Pin
Jarosław Zwierz1-Aug-14 0:04
memberJarosław Zwierz1-Aug-14 0:04 
QuestionSubmit buttons not working in the modal Pin
Neerav Pandya25-Jul-14 20:43
memberNeerav Pandya25-Jul-14 20:43 
AnswerRe: Submit buttons not working in the modal Pin
Jarosław Zwierz29-Jul-14 0:10
memberJarosław Zwierz29-Jul-14 0:10 
QuestionModal Bootstrap Form Pin
Krupskaia Angulo25-Jul-14 5:01
memberKrupskaia Angulo25-Jul-14 5:01 
AnswerRe: Modal Bootstrap Form Pin
Jarosław Zwierz29-Jul-14 0:02
memberJarosław Zwierz29-Jul-14 0:02 
GeneralMy vote of 5 Pin
Maciej Los24-Jul-14 2:10
mvpMaciej Los24-Jul-14 2:10 
QuestionMultiple partial views Pin
Krupskaia Angulo16-Jul-14 16:59
memberKrupskaia Angulo16-Jul-14 16:59 
AnswerRe: Multiple partial views Pin
Jarosław Zwierz23-Jul-14 3:42
memberJarosław Zwierz23-Jul-14 3:42 
GeneralRe: Multiple partial views Pin
Krupskaia Angulo25-Jul-14 4:55
memberKrupskaia Angulo25-Jul-14 4:55 
QuestionSource Code Projects Not Building Pin
Paul Chu5-Jul-14 19:43
memberPaul Chu5-Jul-14 19:43 
AnswerRe: Source Code Projects Not Building Pin
Jarosław Zwierz7-Jul-14 6:17
memberJarosław Zwierz7-Jul-14 6:17 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 24 Feb 2015
Article Copyright 2014 by Jarosław Zwierz
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid