asp.net mvc onsuccess jquery函数委托

时间:2011-12-02 11:23:05

标签: jquery asp.net-mvc

这是我的观点:

@using (Ajax.BeginForm("Accept", "FriendRequest", new { id = m.FriendRequest.Id }, new AjaxOptions { OnSuccess = "DoSomthing" })) {
    <input type="button" value="Accept" onclick="submitAjaxform(this);" />
}

以下是DoSomething函数的签名:

function DoSomthing(a,b,c) {
    alert(a.Status);
}

这是我提交请求的javascript函数:

function submitAjaxform(btn) {
    var form = btn.form;
    var data = $(form).serialize();
    var action = $(form).attr('action');
    var onsuccess = $(form).attr('data-ajax-success');
    $.post(action, $(form).serialize(), function (data, status, xhr) {
         var x = onsuccess + ".apply([" + data + "]);";
         eval(x);
    });
}

这是我的行动方法:

public JsonResult Accept(long id) {
    return Json(new {status=true,message="some message"});
}

当我运行代码时。发布效果很好,但jQuery函数的onsucess在控制台中出现以下错误:

  元素列表

缺少]

我不明白如何修复它。帮助将不胜感激。

编辑:感谢Rich,这是最终有效的

function submitAjaxform(btn) {
    var form = btn.form;
    var data = $(form).serialize();
    var action = $(form).attr('action');
    var onsuccess = $(form).attr('data-ajax-success');
    $.post(action, $(form).serialize(), function (data, status, xhr) {
         window[onsuccess](data);

    });
}

Calling a JavaScript function named in a variable

找到答案

2 个答案:

答案 0 :(得分:0)

您的数据变量在成功回调的范围内是不同的,因为您没有使用在外面声明的那个我假设您的代码应该是:

function submitAjaxform(btn) {
  var form = btn.form;
  var data = $(form).serialize();
  var action = $(form).attr('action');
  var onsuccess = $(form).attr('data-ajax-success');
  $.post(action, $(form).serialize(), function () {
     var x = onsuccess + ".apply([" + data + "]);";
     eval(x);
  });
}

或者,作为回调的第一个参数传递的数据已经是一个对象,所以你只需要评估你的onsuccess,如下所示:

function submitAjaxform(btn) {
  var form = btn.form;
  var action = $(form).attr('action');
  var onsuccess = $(form).attr('data-ajax-success');
  $.post(action, $(form).serialize(), function (data) {
     eval(onsuccess).apply([data]);
  });
}

顺便说一句,我建议尽可能不使用eval,它很昂贵并且允许在浏览器中运行可能不受信任的javascript。如果可以重构您的代码而不需要它,那么您应该。

答案 1 :(得分:0)

我建议采取其他方法......

@model competestreet.com.Models.Page
@{
    ViewBag.Title = "Contact & Support";
    Layout = "~/Views/Shared/_LayoutInner.cshtml";
}

<script src="@Url.Content("~/Scripts/ValidateContactForm.js")" type="text/javascript"></script>
<h2 class="title">
    <span class="text-contact">Contac<span>t</span></span></h2>
<div class="box">
    <div class="t">
    </div>
    <div class="c">
        <div class="content">
            <div class="main-holder">
                <div id="sidebar">
                    <ul>
                        <li class="active"><a href="#">General</a></li>
                        <li><a href="#">Our Mission</a></li>
                        <li><a href="#">Sub Navigation</a></li>
                        <li><a href="#">Sub Navigation</a></li>
                    </ul>
                </div>
                <div id="content">

                    <form class="cmxform" id="contactForm" method="get" action="">
                    <div id="contactFormFields">

                    <table>
                        <tr>
                            <td style="width: 150px;">
                                E-Mail
                            </td>
                            <td>
                                <input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                                Name
                            </td>
                            <td>
                                <input id="cname" name="name" type="text" value="Name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                                Subject
                            </td>
                            <td>
                                <input id="csubject" name="subject" type="text" value="Subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px; vertical-align: top;">
                                Message
                            </td>
                            <td>
                                <textarea id="cmessage" maxlength="1000" type="text" value="Your Message" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 150px;">
                            </td>
                            <td>
                                <input type="submit" value="Send" class="input-btn" onclick="SendContactForm(); return false;" style=" width:100px; color: Black;" />
                            </td>
                        </tr>
                    </table>

                    </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="b">
    </div>
</div>

ValidateContactForm.js的JavaScript:

$('#thankYou').hide();

var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
    return String(s).search(isEmail_re) != -1;
}

function isBlank(s) {
    if (!s || s.length == 0) {
        return true;
    }
    // checks for a non-white space character 
    // which I think [citation needed] is faster 
    // than removing all the whitespace and checking 
    // against an empty string
    return !/[^\s]+/.test(s);
}


function SendContactForm() {
    var isFormValid = true; 

    var isEmailOk = isEmail($('#cemail').val());
    if (isEmailOk == false) {
        $('#emEmail').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emEmail').css('color', 'black');
    }

    var isNameOk = isBlank($('#cname').val());
    if (isNameOk) {
        $('#emName').css('color', 'red');
        isFormValid = false;
        //alert('!');
    }
    else {
        $('#emName').css('color', 'black');
    }

    var isSubjectOk = isBlank($('#csubject').val());
    if (isSubjectOk) {
        $('#emSubject').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emSubject').css('color', 'black');
    }

    var isMesageOk = isBlank($('#cmessage').val());
    if (isMesageOk) {
        $('#emMessage').css('color', 'red');
        isFormValid = false;
    }
    else {
        $('#emMessage').css('color', 'black');
    }

    if (isFormValid) {
        $.post("/Home/SendContactForm", { email: $('#cemail').val(),
            name: $('#cname').val(),
            subject: $('#csubject').val(),
            message: $('#cmessage').val()
        },
                 function (data) {
                         $('#contactFormFields').hide('slow');
                    if (data.length > 0) {
                          $('#contactForm').html(data);
                          $('#thankYou').show('fast');                       
                        }
         });
    }
}

和C#

public JsonResult SendContactForm(string email, string name, string subject, string message)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<div id='thankYou' class='thankyou'>Thank you! We are going to contact you as soon as it possible!</div>");
    return Json(sb.ToString());
}

所以你不需要使用Ajax.BeginForm()