开发者

ASP.NET MVC - Form Post always redirect when I just want to bind json result to a div

开发者 https://www.devze.com 2023-01-31 16:10 出处:网络
I\'m having a little problem with json result. I\'m submitting a contact form, and after the submission, I just want to return some json data (indicating either a success or failed and displays a mess

I'm having a little problem with json result. I'm submitting a contact form, and after the submission, I just want to return some json data (indicating either a success or failed and displays a message) back to the view, without causing a redirect, but it kept redirecting me to the action, here are the codes:

HTML

<div id="contactForm2" class="grid_6">
        <div id="contactFormContainer">
            @using (Html.BeginForm(MVC.Home.ActionNames.ContactForm, MVC.Home.Name, FormMethod.Post, new { id = "contactForm" }))
            {
                <p>
                    <input type="text" tabindex="1" size="22" value="" id="contactName" class="text_input required"
                        name="contactName" />
                    <label for="contactName">
                        <strong class="leftSpace">Your Name (required)</strong></label></p>
                <p>
                    <input type="text" tabindex="2" size="22" value="" id="contactEmail" class="text_input required"
                        name="contactEmail" />
                    <label for="contactEmail">
                        <strong class="leftSpace">Email (required)</strong></label></p>
                <p>
                    <input type="text" tabindex="2" size="22" value="" id="contactPhone" class="text_input"
                        name="contactPhone" />
                    <label for="contactPhone">
                        <strong class="leftSpace">Phone</strong></label></p>
                <p>
                    <label>
                        <strong class="leftSpace n">Message (required)</strong></label>
                    <textarea tabindex="4" rows="4" cols="56" id="contactMessage" class="text_area required"
                        name="contactMessage"></textarea></p>
                <p>
                    <input type="submit" value="Send" tabindex="5" id="contactSubmit" class="button submit"
                        name="contactSubmit" /></p>
            }
        </div>
        <div id="contactFormStatus">
        </div>
    </div>

Controller

[HttpPost]
        public virtual JsonResult ContactForm(FormCollection formCollection)
        {
            var name = formCollection["contactName"];
            var email = formCollection["contactEmail"];
            var phone = formCollection["contactPhone"];
            var message = formCollection["contactMessage"];

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(message))
            {
                return Json(new { success = false, message = "Please complete all the required fields so that I can get back to you. Thanks." }开发者_如何学C);
            }

            // Insert contact form data here...

            return Json(new { success = true, message = "Your inquery has been sent. Thank you." });
        }

javascript

$(document).ready(function () {
    $('#contactSubmit').live('click', function () {
        var form = $('#contactForm');
        var formData = form.serialize();

        $.post('/Home/ContactForm',
        formData,
        function (result) {
            var status = $('#contactFormStatus');
            if (result.success) {
                $('#contactForm')[0].reset;
            }
            status.append(result.message);
        },
        'json'
        );
        return false;
    });
});

I've also tried this javascript, but also got a redirect

$(document).ready(function () {
    $('#contactSubmit').live('click', function () {
        var form = $('#contactForm');
        var formData = form.serialize();

        $.ajax({
            type: 'POST',
            url: '/Home/ContactForm',
            data: formData,
            success: function (result) {
                SubmitContactResult(result);
            },
            cache: false
        });
    });

    function SubmitContactResult(result) {
        var status = $('#contactFormStatus');

        if (result.success) {
            $('#contactForm')[0].reset;
        }

        status.append(result.message);
    }
});

Any idea what's going on with my code?

Thank you very much.


There are many things going on with your code and I will try to cover most of them.

The fact that you are getting a redirect means that you have an error somewhere in your javascript. I would start by the following simplification of your code. Personally I prefer subscribing to the submit event of the form instead of the click event of a submit button:

$(function() {
    $('#contactForm').submit(function() {
        $.ajax({
            type: this.method,
            url: this.action,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#contactForm')[0].reset();
                }
                $('#contactFormStatus').text(result.message);
            }
        });
        return false;
    });
});

Also notice that you probably want:

$('#contactForm')[0].reset();

instead of:

$('#contactForm')[0].reset;

Another thing I've noticed is that you probably want:

$('#contactFormStatus').text(result.message);

instead of:

$('#contactFormStatus').append(result.message);

because result.message is a plain string returned by your controller, it doesn't represent any DOM element which is what the .append() function expects.

There might also be other errors. My eyes are tired. Use FireBug, it will tell you all the errors you've got in your scripts and once you've fixed them all it's gonna work.


UPDATE:

I forgot to mention that because what you have is a common scenario (AJAXifying a form) people have written a jquery plugin for it so that you don't have to go through all the pain over and over again and so that you simply could have:

$(function() {
    $('#contactForm').ajaxForm(function(result) {
        if (result.success) {
            $('#contactForm')[0].reset();
        }
        $('#contactFormStatus').text(result.message);
    });
});

Now that's much better, isn't it?

Also your controller action looks messy with all those magic strings. How about using a view model:

public class ContactViewModel
{
    [Required]
    public string ContactName { get; set; }

    [Required]
    public string ContactEmail { get; set; }

    public string ContactPhone { get; set; }

    [Required]
    public string ContactMessage { get; set; }
}

and then simply:

[HttpPost]
public ActionResult ContactForm(ContactViewModel contact)
{
    if (!ModelState.IsValid)
    {
        return Json(new { 
            success = false, 
            message = "Please complete all the required fields so that I can get back to you. Thanks." 
        });
    }

    // Insert contact form data here...
    return Json(new { 
        success = true, 
        message = "Your inquery has been sent. Thank you." 
    });
}

Now we've got something much cleaner.

And all that's left is to clean your view by taking advantage of the view model and strongly typed helpers:

<div id="contactForm2" class="grid_6">
    <div id="contactFormContainer">
        @using (Html.BeginForm(MVC.Home.ActionNames.ContactForm, MVC.Home.Name, FormMethod.Post, new { id = "contactForm" })) {
            <p>
                @Html.TextBoxFor(x => x.ContactName, new { tabindex = "1", size = "22", @class = "text_input required" })
                @Html.LabelFor(x => x.ContactName, "Your Name (required)")
            </p>
            <p>
                @Html.TextBoxFor(x => x.ContactEmail, new { tabindex = "2", size = "22", @class = "text_input required" })
                @Html.LabelFor(x => x.ContactEmail, "Email (required)")
            </p>
            <p>
                @Html.TextBoxFor(x => x.ContactPhone, new { tabindex = "3", size = "22", @class = "text_input" })
                @Html.LabelFor(x => x.ContactPhone, "Phone")
            </p>
            <p>
                @Html.LabelFor(x => x.ContactMessage, "Message (required)")
                @Html.TextAreaFor(x => x.ContactMessage, 4, 56, new { tabindex = "4", @class = "text_input required" })
            </p>
            <p>
                <input type="submit" value="Send" tabindex="5" id="contactSubmit" class="button submit" name="contactSubmit" />
            </p>
        }
    </div>
    <div id="contactFormStatus">
    </div>
</div>


Ive done it the following way with $.post()

$('#contactForm').live('submit', function () {
//rest of code
});
0

精彩评论

暂无评论...
验证码 换一张
取 消