Share via


Simple JSOn code for contact form

Question

Saturday, March 23, 2013 12:57 AM

Hi, Could you please any one help me out a simple lines of code submitting contact form by using json, please

All replies (3)

Saturday, March 23, 2013 4:35 AM ✅Answered

please see http://bit.ly/mvc_ajax_jquery


Saturday, March 23, 2013 5:30 AM ✅Answered

I submit to you in the following a simple contact form based on the _SiteLayout.cshtml layout file of the Starter Site template:

@section Scripts {
    <script>
        function SendData() {
            $.ajax({
                type: "POST",
                url: $("#myForm").attr('action'),
                data: $("#myForm").serialize(),
                success: function (response) {
                    alert('Comment sent');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        };
    </script>   
}

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Contact Form";
}

<hgroup class="title">
    <h4>@Page.Title.</h4>
    <h4>Let us know your opinion.</h4>
</hgroup>

<form name="myForm" id="myForm" action="~/ContactHandler">
    <fieldset>
        <legend>Contact form</legend>
        <ol>
            <li class="name">
                <label for="name">Name</label>
                <input type="text" id="name" name="name" />
            </li>
            <li class="email">
                <label for="email">Email</label>
                <input type="text" id="email" name="email" />
            </li>
            <li class="comment">
                <label for="comment">Comment</label>
                <textarea id="comment" name="comment"></textarea>
            </li>
        </ol>
        <input type="button" value="Send" onclick="SendData()"/>
    </fieldset>
</form>

and this is the ContactHandler.cshtml file:

@{
    Layout = null;
        if(IsPost) {
        var name = Request["name"];
        var email = Request["email"];
        var comment = Request["comment"];

        var db = Database.Open("StarterSite");
        var result = db.Execute(@"INSERT INTO Contacts (Name, Email, Comment) 
                VALUES (@0, @1, @2)", name, email, comment);

        WebMail.Send(
            to: email, 
            subject: "Your Opinion",
            body: "Hello, " + name + ", your comment was:<br/>'" + comment + "'.<br/><br/>See you."
        );
    }
}

As you can see, whenever the user submits a comment a record is added to the Contacts table (you must add it to your db) and a message is sent to the user (you must modify your _AppStart.cshtml file adding the SMTP server parameters).

I have mainly grabbed the ajax function from this Mike Brind's article: WebMatrix And jQuery Forms.

If you want to create a modal contact form you can take useful hints from it.


Saturday, March 23, 2013 11:40 AM

Thanks much GmGregori. Your code is very useful for me.