简体   繁体   English

如何将 Jquery/Ajax 与 asp.net MVC 4 与部分视图和动作与模型一起使用

[英]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.我是 ASP.NET MVC 和 JQuery 的新手,所以要温柔。

I am trying to use a HTTP Post to update my contact form, used to send an email, using AJAX.我正在尝试使用 HTTP Post 来更新我的联系表单,用于使用 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.结束了这个,但下次会尝试“serialize()”选项。 controller was changed to this without the [ChildActionOnly] and works perfect now控制器在没有 [ChildActionOnly] 的情况下更改为这个,现在工作完美

   [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将控制器中的[ChildActionOnly]更改为[HttpGet]
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 1.点击提交时获取input值并发送到控制器中的Footer动作

    $("#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
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReferenceError: 'x' 未定义 - asp.net mvc 部分视图和 jQuery/JavaScript - 将整个 model 传递给操作方法 - ReferenceError: 'x' is not defined - asp.net mvc partial view and jQuery/JavaScript - passing the entire model to an action method 如何使用jquery添加或删除部分视图Asp.net mvc? - How to add or remove partial view Asp.net mvc with jquery? 如何在部分视图(ASP.NET MVC)中使用DevExtreme? - How to use DevExtreme in partial view (ASP.NET MVC)? 如何使用AJAX Post调用ASP.NET MVC Controller操作并返回新的View? - How to use AJAX Post to invoke ASP.NET MVC Controller action and return new View? ASP.NET MVC部分查看ajax帖子? - ASP.NET MVC Partial view ajax post? 在部分视图asp.net mvc中的文本框上进行jquery聚焦 - jquery focusout on a textbox in partial view asp.net mvc 在ASP.NET MVC中使用jQuery渲染局部视图 - Render Partial View Using jQuery in ASP.NET MVC ASP.NET MVC在部分视图中使用javascript值 - ASP.NET MVC Use javascript value in partial view 是否可以在 ASP.NET MVC 的局部视图上使用一些 JavaScript? - Is it possible use some JavaScript on a Partial View in ASP.NET MVC? 在不使用jQuery的情况下使用MS Ajax在ASP.NET MVC 2中调用操作 - Call an action in ASP.NET MVC 2 with MS Ajax without jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM