简体   繁体   中英

How to use Jquery/Ajax with asp.net MVC 4 with partial view and action with model

I am new to both asp.net MVC and JQuery so be gentle.

I am trying to use a HTTP Post to update my contact form, used to send an email, using AJAX. I have seen lots of posts but what I want seems specific and I cant seem to find anything relevant.

The down low: I have a layout page which has the header, renders the body and has my footer in. My footer contains the form I want to submit. I want to submit this form without refreshing the whole page. The layout page:

    <div id="footer">

        @{Html.RenderAction("Footer", "Basic");}

    </div>

<p id="p"></p>

I have a model for this form to send an email.

namespace SimpleMemberShip.Models
{
    public class EmailModel
    {


        [Required, Display(Name = "Your name")]
        public string FromName { get; set; }
        [Required, Display(Name = "Your email"), EmailAddress]
        [StringLength(100, ErrorMessage = "The email address entered is not valid")]
        public string FromEmail { get; set; }
        [Required]
        public string Message { get; set; }

}

The footer:

 <h2> footer yo !</h2>

@Html.ValidationSummary()

<fieldset>
        <legend>Contact Me!</legend>

        <ol>
            <li>
                @Html.LabelFor(m => m.FromEmail)
                @Html.TextBoxFor(m => m.FromEmail)
            </li>
            <li>
                @Html.LabelFor(m => m.FromName)
                @Html.TextBoxFor(m => m.FromName)
            </li>
            <li>
                @Html.LabelFor(m => m.Message)
                @Html.TextBoxFor(m => m.Message)
            </li>
        </ol>

        <button id="submit"> Submit </button>

</fieldset>   

controller:

      [ChildActionOnly]
    public ActionResult Footer()
    {

        return PartialView("~/Views/Shared/_Footer.cshtml");


    }

    [HttpPost]
    public ActionResult Footer(EmailModel model)
    {

         return PartialView("~/Views/Shared/_Footer.cshtml"); 
    }

I want to use the model validation and everything to be the same or similar as if the form was posted normally through the server.

Edit: My new code, which works great! but it only works once, when the button is clicked again nothing happens. Anyone know why?

 <script type="text/javascript">


$("#submit").click(function () {

    $("#footer").html();
        var url = '@Url.Action("Footer", "Basic")';
        $.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $("  [name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data)    {

             $("#footer").html(data);

        });

        var name = $("[name=FromName]").val();
        $("#p").text(name);

    });

</script>

new Edit:

did some research and using

$("#submit").live("click",function () {

instead of

 $("#submit").click(function () {

seemed to do the trick.

<script type="text/javascript">


$("#submit").live("click",function () {
    $('.validation-summary-errors').remove();
        var url = '@Url.Action("Footer", "Basic")';
        $.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $("[name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {

            $("#footer").html(data);

        });


    });

</script>

ended up with this but will try the "serialize()" option next time. controller was changed to this without the [ChildActionOnly] and works perfect now

   [HttpPost]
    public ActionResult Footer(EmailModel model)
    {
            return PartialView("~/Views/Shared/_Footer.cshtml");
    }

Thank you everyone that helped!

Change the [ChildActionOnly] to [HttpGet] in the controller
You can pass model data to controller by doing the following steps
1. Get the input values on click of submit and sent to the Footer action in controller

    $("#submit").click(function () {
        var FromEmailValue = $('#FromEmail').val();
        var FromNameValue = $('#FromName').val();
        var MessageValue = $('#Message').val();
        var url = '@Url.Action("Footer", "Basic")';
        $.ajax({
             url: urlmodel,
            data: { FromName: FromNameValue, FromEmail: FromEmailValue, Message: MessageValue},
            cache: false,
            type: "POST",
            success: function (data) {
                do something here
            }
            error: function (reponse) {
                do something here
            }
        });
    });
  1. In the controller

``

    [HttpGet]
    public ActionResult Footer()
    {
        return PartialView("~/Views/Shared/_Footer.cshtml");
    }

[HttpPost]
    public ActionResult Footer(string FromName = "", string FromEmail = "", string Message = "")
    {
        //for ajax request
        if (Request.IsAjaxRequest())
        {
            do your stuff
        }
    }

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