【问题标题】:Submit Form in foreach Loop and call ajax function mvc 4 with it's data only在 foreach 循环中提交表单并仅使用其数据调用 ajax 函数 mvc 4
【发布时间】:2017-05-11 01:48:08
【问题描述】:

在我看来:

@foreach (var item in Model)
{
    // some code
    <form method="post" id="myForm" onsubmit="if (!onformsubmitContactUs()) { return false; }">
        <input type="text" value="4" name="id" style="display: none;" />
        <input type="text" name="Name" id="Name" placeholder="الاسم" required>
        <textarea name="Msg" id="Msg" placeholder="تعليق" required></textarea>
        <input type="submit" id="b" value="ارسال">
    </form>
}

Ajax 函数:

<script type="text/javascript">

function onformsubmitContactUs() {
    if ($('#Name').val() != '' && $('#Msg').val() != '') {
        return true;
    }
    else {
        if ($('#Name').val() == '') { $('#Name').css("borderColor", "red"); } else { $('#Name').css("borderColor", ""); }
        if ($('#Msg').val() == '') { $('#Msg').css("borderColor", "red"); } else { $('#Msg').css("borderColor", ""); }
        return false;
    }


};

$(document).ready(function () {
$('#myForm').on('submit', function (event) {
    event.preventDefault();
    if (!onformsubmitContactUs()) return false;
    $.ajax({
        url: '@Url.Action("AddComment", "Home")',
        type: 'post',
        data: $('#myForm').serialize(),
        beforeSend: function () {

            $('#b').val('sending .......'); // change submit button text
            $('#Name').css("borderColor", "");
            $('#Msg').css("borderColor", "");
        },
        success: function (response,textStatus, jqXHR) {
            // There is no problem with the validation
            if (response) {
                $('#b').val('success');
                document.getElementById("myForm").reset();
                $('#Name').css("borderColor", "");
                $('#Msg').css("borderColor", "");
            }
            // Problem happend during the validation, display message related to the field.
            $.each(data.Errors, function (key, value) {
                if (value != null) {
                    //$("#Err_" + key).html(value[value.length - 1].ErrorMessage);
                    $("#" + key).css("borderColor", "rgba(247, 5, 5, 0.53)");
                    $('#b').html('send');
                    $('#result').text("");
                }
            });
        }
    });
   });
});


</script>

动作控制器:

    public bool AddComment()
    {
        bool result = false;
        EventComment cuM = new EventComment();
        string Name = Request.Form["Name"], Email = Request.Form["Email"],
                     Message = Request.Form["Msg"];

        cuM.EventId = int.Parse(Request.Form["id"]);
        cuM.Name = Name;
        cuM.Comment = Message;
        cuM.IsSeen = false;
        cuM.IPAddress = Request.ServerVariables["REMOTE_ADDR"];
        cuM.DateAdd = DateTime.Now;
        cuM.Approval = false;
        db.EventComments.Add(cuM);

        db.SaveChanges();
        result = true;

        return result;
    }

当提交我的表单在 foreach 循环中包含所有数据时,如果内容在循环后有 3 个表单,则 Form.Request 具有这样的所有数据:

{id=1,id=2,id=3,Name="00",Name="",Name="",Msg="",...}

什么错误。

如何让每个表单只使用其数据调用 ajax?

【问题讨论】:

    标签: jquery ajax asp.net-mvc forms


    【解决方案1】:

    id 属性在同一个元素中应该是唯一的,并且您拥有所有具有相同 id 的表单,因此请将那些 id 替换为通用类,例如:

    <form method="post" class="myForm" ...>
        <input type="text" value="4" name="id" style="display: none;" />
        <input type="text" name="Name" class="Name" placeholder="الاسم" required>
        <textarea name="Msg" class="Msg" placeholder="تعليق" required></textarea>
        <input type="submit" class="b" value="ارسال">
    </form>
    

    然后在你的 js 中用类替换每次使用 #b/#myForm/#Name/#Msg,例如:

    $('.myForm').on('submit', function (event) {
        event.preventDefault();
        if (!onformsubmitContactUs()) return false;
    
        var _this = $(this);
    
        $.ajax({
            url: '@Url.Action("AddComment", "Home")',
            type: 'post',
            data: _this.serialize(),
            beforeSend: function () {
                $('.b',_this).val('sending .......'); // change submit button text
                $('.Name',_this).css("borderColor", "");
                $('.Msg',_this).css("borderColor", "");
            },
            ....
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      相关资源
      最近更新 更多