简体   繁体   中英

How do I create an empty form inside a popup in asp.net mvc?

I have a built a form in asp.net mvc (the left side is what I've built, the right side is what I'd like to add):

发送测试电子邮件概念

I'd like the Send Test Email button to launch a popup window that has a blank form. One textbox to enter the recipient's email, another to enter the sender's email, and a button to send the email. Now this popup needs to gather a few fields from the main form that launched it: Subject and Body (body not shown in the screenshot). How can I do this? I won't know the two email addresses ahead of time, so they wouldn't already exist in a model object. Here's some of my code so far (in a view called EmailTemplate.cshtml):

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" /> &nbsp;&nbsp;                    
                <button id="btnSendTestEmail">Send Test Email</button>

                <div id="SendTestEmail"></div>

            </div>
        </div>

That's for the initial button to launch the popup and for the area to place it on the page. And here's the javascript I'm starting to write, but am not sure how to finish:

var url = '@Url.Action("SomeActionHere","SomeControllerHere")';

    $('#btnSendTestEmail').click(function () {
        $("#SendTestEmail").load(url);
    });

It seems like I have to create an action method, but I don't know why, because I don't need to prepopulate the two email textboxes. And I also seem to have to specify a controller, but I don't know if that controller is meant to prepopulate the form or handle the form when it's submitted (when the send test email button on the popup is clicked) I've created a partial view called EmailTestForm.cshtml:

@model EmailTemplateEditor.Models.TestEmail

<form id="SendTestEmail">

    Recipient Email Address: @Html.TextBox("RecipientEmail")
    Sender Email Address: @Html.TextBox("SenderEmail")
    <br/>
    <input type="submit" value="Send Test Email" class="btn btn-default" /> 

</form>

And I even created a model for this, though I'm not sure I need to (I'm new to mvc and it still feels like I'm often shoehorned into making lots and lots of models)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EmailTemplateEditor.Models
{
    public class TestEmail
    {        
        public string RecipientEmail { get; set; }

        public string SenderEmail { get; set; }
    }
}

Ultimately, when the popup's send test email button is clicked, I want to grab the 2 email addresses, the body and subject from the main form, pass them into an method where I can pass them into a stored procedure call. Am I even approaching this the right way here, or am I way off? I've found a few SO posts that are somewhat like this case, but different enough for me to still feel lost.

I figured it out. I had to make several changes:

  1. Move my modal div to outside of containing page's form
  2. Display the modal div when a button was clicked (per Stephen Muecke's comment)
  3. Move the submit javascript code for when the test email button is clicked from the containing page into the partial view page.
  4. Add onclick="SubmitAction()" to the submit button

Here's my final code (shortened):

EmailTemplate.cshtml (the containing page)

@model EmailTemplateEditor.Models.EmailTemplate

@{
    ViewBag.Title = "Email Template";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Email Template</h2>

@using (Html.BeginForm("Edit", "EmailTemplate", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">        
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.ID)

            <div class="form-group">
                @Html.LabelFor(model => model.Subject, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Subject)
                    @Html.ValidationMessageFor(model => model.Subject)
                </div>
            </div>                        

            <div class="form-group" tabindex="-1">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" /> &nbsp;&nbsp;
                    <a id="btnSendTestEmail">Send Test Email</a>

                    <div id="SendTestEmail"></div>

                </div>
            </div> 
    </div>
}

<div class="modal" id="SendTestEmailModal">
    <div class="modal-content">
        @Html.Partial("EmailTestForm", new EmailTemplateEditor.Models.TestEmail(Model.Body, Model.Subject))
        <span class="close">&times;</span>
    </div>
</div>

<script>

    $(document).ready(function () {                 
        var span = document.getElementsByClassName("close")[0];
        var modal = document.getElementById('SendTestEmailModal');        

        // When the user clicks on the button, open the modal 
        $('#btnSendTestEmail').click(function () {
            //$("#SendTestEmailModal").show();
            modal.style.display = "block";
        });

        // When the user clicks on <span> (x), close the modal
        span.onclick = function () {
            modal.style.display = "none";
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }                                      
    });
</script>

Here's the partial view (EmailTestForm.cshtml):

@model EmailTemplateEditor.Models.TestEmail

<body>

    @using (Html.BeginForm("SendTestEmail", "EmailTemplate", FormMethod.Post, new { id = "SendTestEmailForm" }))
    { 
        <table class="module">                     
            <tr>
                <td>Subject:</td>
                <td> @Html.TextBoxFor(m => m.Subject, new { id = "txtSubject" })</td>
                <td>Body:</td>
                <td>@Html.TextBoxFor(m => m.Body, new { id = "txtBody" })</td>
            </tr>
        </table>
        <br /><br />
        <input type="submit" value="Send Test Email" class="btn btn-default" onclick="SubmitAction()"/>
    }

    <script>
        $(document).ready(function () {            
            function SubmitAction() {                
                var data = $("#SendTestEmailForm").serialize();

                $.ajax({
                    type: "Post",
                    url: "@Url.Action("SendTestEmail", "EmailTemplate")",
                    data: data,
                    success: function (partialResult) {
                        $("#modal-content").html(partialResult);
                    }
                })
            }            
        });
    </script>
</body>

Here's the relevant controller function (EmailTemplateController.cs):

[HttpPost]
public void SendTestEmail(TestEmail model)
{   
    if (ModelState.IsValid)
    {               
        Worker.SendMCTestEmail(model.SenderEmail, model.RecipientEmail, model.SenderName, model.RecipientName, model.Subject, model.Body, model.RecipientFirstName, model.RecipientLastName);       
    }   
}

Here's the css for the modal (in main.css):

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 100000000; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #000;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM