Users Pricing

articles

home / developersection / articles / custom model popup in mvc 4 razor

Custom Model Popup in MVC 4 Razor

AVADHESH PATEL 38204 30 Nov 2012 Updated 17 Sep 2019

Here I’m going to describe how to create custom confirm dialog box in ASP.NET MVC 4. Steps are given below.

Step1: Open project with “Internet Application” option, because it provide inbuilt

jQuery and CSS.

Step 2: First we create a model for display and save data.

using System.Collections.ObjectModel;

using System.Linq;
using System.Web;
 
namespace Website.Models
{
    public class Note
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }
    public class NoteManager
    {
        public Collection<Note> Notes
        {
            get
            {
                if (HttpRuntime.Cache["Notes"] == null)
                    this.loadInitialData();
                return (Collection<Note>)HttpRuntime.Cache["Notes"];
            }
        }
 
        private void loadInitialData()
        {
            var notes = new Collection<Note>();
            notes.Add(new Note
                            {
                                Id = 1,
                                Title = "Set DVR for Sunday",
                                Body = "Don't forget to record Game of Thrones!"
                            });
            HttpRuntime.Cache["Notes"] = notes;
        }
 
        public Collection<Note> GetAll()
        {
            return Notes;
        }
 
        public Note GetById(int id)
        {
            return Notes.Where(i => i.Id == id).FirstOrDefault();
        }
 
        public int Save(Note item)
        {
            if (item.Id <= 0)
                return saveAsNew(item);
            var existingNote = Notes.Where(i => i.Id == item.Id).FirstOrDefault();
            existingNote.Title = item.Title;
            existingNote.Body = item.Body;
            return existingNote.Id;
        }
 
        private int saveAsNew(Note item)
        {
            item.Id = Notes.Count + 1;
            Notes.Add(item);
            return item.Id;
        }
    }
}

Step 3: Create controller (e.g. HomeController) and View (e.g. Index) in ASP.NET MVC 4. And copy paste below code

Controller
using System.Web.Mvc;

using Website.Models;
 
namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult List()
        {
            var manager = new NoteManager();
            var model = manager.GetAll();
            return PartialView(model);
        }
 
        public ActionResult Create()
        {
            var model = new Note();
            return PartialView("NoteForm", model);
        }
 
        [HttpPost]
        public ActionResult Save(Note note)
        {
            var manager = new NoteManager();
            manager.Save(note);
            var model = manager.GetAll();
            return PartialView("List", model);
        }
    }
}

 View


<div id="NoteListBlock"></div>
<span class="AddLink ButtonLink">Add New Data</span>
<div id="NoteDialog" title="" class="Hidden"></div>

 Step 4: Now, we create two partial views (e.g. List and NoteForm) for display data on view and within model popup.

Partial View – List
@model IEnumerable<Website.Models.Note>

<ul class="NotesList">
    @foreach (var data in Model)
    {
    <li>
        @data.Id<br />
        @data.Title <br />
        @data.Body <br />
 
    </li>
    }
</ul>
Partial View – NoteForm
@model Website.Models.Note

@using(Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "NoteForm" })) {
@Html.Hidden("Id")
<label class="Title">
    <span>Title</span><br />
    @Html.TextBox("Title")<br />
</label>
<label class="Body">
    <span>Body</span><br />
    @Html.TextArea("Body")
</label>
}
    <script type="text/javascript">
        $(function () {
            $("#NoteForm").validate({
                rules: {
                    Title: { required: true },
                    Body: { required: true }
                }
            });
        });
    </script>

 Step 5: Now in final Step include CSS and jQuery file on _Layout view.  

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="Stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
</head>
<body>
    <script type="text/javascript">
        $(function () {
            $("#NoteDialog").dialog({
                autoOpen: false, width: 400, height: 500, modal: true,
                buttons: {
                    "Save": function () {
                        if ($("#NoteForm").validate().form()) {
                            $.post("/Home/Save",
        $("#NoteForm").serialize(),
        function (data) {
            $("#NoteDialog").dialog("close");
            $("#NoteListBlock").html(data);
        });
                        }
                    },
                    Cancel: function () { $(this).dialog("close"); }
                }
            });

            $(".AddLink").click(function () {
                $("#NoteDialog").html("")
                .dialog("option", "title", "Add Note")
                .load("/Home/Create", function () { $("#NoteDialog").dialog("open"); });
            });
            LoadList();
        });
        function LoadList() {
            $("#NoteListBlock").load("/Home/List");
        }
    </script>
    @RenderBody()
</body>
</html>

Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)


1 Comments