PartialView into a Modal from a button click

In this example the first bit of code is on the main page. It consists of a button and PartialView. The partial view is actually a bootstrap modal window so you won’t see it at all when the page initially loads, but once the user clicks the button, it will open the modal window from the partial view:

@Html.Partial(“ModalPartial”, new ModalTaskManageViewModel() { ModalTaskId = 0, ModalTaskParentId = Model })

        <!– Button trigger modal –>

        @if (Model > 0)

        {

            <button class=”btn btn-link ” data-toggle=”modal” data-target=”#modalTaskModal”>

                Create Subtask

            </button>

        }

The partialView contains the following code. What you need to understand about this is that your form attributes set this as a AJAX form so it can post back data without doing a full postback of the window, and the insertionMode tells it to reload the data within the ‘Modal_TaskPartial’ tags. This way if the form submits but isn’t done because of something like invalid input, it can continue to stay on this modal form.

If a post back is successful, the C# code in the cotroller must call some javascript to make the modal disappear. I’ll show that further down the page.

@model ModalTaskManageViewModel

           @{

               var baseurl = Request.Url.Scheme + “://” + Request.Url.Authority;

           }

<!– Modal –>

<div class=”modal fade” id=”modalTaskModal” tabindex=”-1″ role=”dialog” aria-labelledby=”modalTaskModalLabel” aria-hidden=”true”>

    <div class=”modal-dialog”>

        <div class=”modal-content”>

            <div class=”modal-header”>

                <button type=”button” class=”close” data-dismiss=”modal”><span aria-hidden=”true”>&times;</span><span class=”sr-only”>Close</span></button>

                <h4 class=”modal-title” id=”modalTaskModalLabel”>Manage task</h4>

            </div>

            <div class=”modal-body”>

                <div id=”ModalTask_Partial”>

                    @using (Ajax.BeginForm(“ModalPartial”, “Task”,

        new AjaxOptions

        {

            HttpMethod = “Post”,

            InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,

            UpdateTargetId = “ModalTask_Partial”

        }, new { area = “TaskMgmt”, @class = “form-horizontal”, @role = “form” }))

                    {

                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(false)

                        @Html.HiddenFor(model => model.ModalTaskId)

                       

                        <input class=“btn btn-primary btn-sm” type=“submit” value=“Save” />

                       

                     

                           

                            

                    }

                </div>

            </div>

            <div class=”modal-footer”>

                <button type=”button” class=”btn btn-default” data-dismiss=”modal”>Close</button>

                

            </div>

        </div>

    </div>

</div>

Now we need to see how to handle the form being submitted in your controller. Here is the meat of the function:

[HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult ModalPartial(ModalTaskManageViewModel vm, FormCollection fc)

        {

            PopulateFKLists();

            if (!ModelState.IsValid)

            {

                TempData[“ModalTask_ErrorMessage”] = “Error trying to save object.”;

                return PartialView(vm);

            }

            else

            {

                try

                {

                   “removed code here for readability…”

                  

                    if (entity.Id > 0)

                    {

                        //TempData[“Message”] = “Changes saved.”;

                        return JavaScript(“location.reload(true)”);

                    }

                    else

                    {

                        //TempData[“Message”] = “Item created successfully.”;

                        return JavaScript(“location.reload(true)”);

                    }

                }

                catch (Exception ex)

                {

                    //LogHelper.Log.Error(ex);

                    //TempData[“ModalTask_ErrorMessage”] = “Error trying to save object.”;

                 

                    return PartialView(vm);

                }

            }

        }

Notice that if everything is great and it is done, it uses a javascript function to reload the page, which will make the modal go away as it redisplays the page it was called from.  Otherwise it returns the PartialView to be reviewed or fixed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s