我的Ajax.BeginForm中的OnSuccess脚本传递错误的数据

时间:2014-07-22 15:57:25

标签: javascript jquery ajax asp.net-mvc razor

我正在开发一个as.net mvc Web应用程序。我有以下Ajax.BeginForm: -

@using (Ajax.BeginForm("AddServerToRack", "Server", new AjaxOptions

{
    InsertionMode = InsertionMode.InsertBefore,
    UpdateTargetId = "result",
    LoadingElementId = "progressdialog",
    HttpMethod= "POST"
    ,
    OnSuccess = "addserver",
    OnFailure = "createfail"




}))
{

调用以下操作方法: -

  [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckUserPermissions(Action = "Edit", Model = "Server")]
        [OutputCache(CacheProfile = "NoCache")]
        public ActionResult AddServerToRack(AddServerToRack s)
        {


            try
            {
                //code goes here
                repository.Save();

                return Json(new { IsSuccess = true, Update="",description = "Server Added Successfully.",rackid = s.rackID }, JsonRequestBehavior.AllowGet);

            }
            catch (DbUpdateConcurrencyException exception)
            {


                return Json(new { IsSuccess = false, description = "Record was Modified by another User." }, JsonRequestBehavior.AllowGet);




            }

            catch (DbUpdateException exception)
            {

                string error = String.IsNullOrEmpty(exception.InnerException.InnerException.Message) ? exception.InnerException.ToString() : exception.InnerException.InnerException.Message.ToString();
                return Json(new { IsSuccess = false, description = "Error occurred." + error }, JsonRequestBehavior.AllowGet);


            }
            catch (Exception e)
            {
                return Json(new { IsSuccess = false, description = "Error occurred." }, JsonRequestBehavior.AllowGet);
            }



        }

以及以下OnSuccess脚本: -

function addserver(data) {
    if (data.IsSuccess = true) {

        $('#progress').show();
        $.ajax({
            url: '/Rack/RackServer',
            type: 'GET',
            data: {
                id: data.rackid
            },

            dataType:'html' ,
            //error: function (xhr) {
            //    alert('Error: ' + xhr.statusText);
            //},
            success: function (result) {
                $('#RackDetails').html(result);
                $('#progress').hide();
            },

        });

        jAlert(data.description, 'Creation Confirmation');
    }
    else if (data.IsSuccess = false)
    {
        jAlert(data.description,'Error');

    }
}

但我遇到的问题是,即使data.IsSuccess值为false,脚本内的$.ajax({调用也会执行。因此,脚本似乎不会执行if语句检查,并且即使IsSuccess不等于true,也始终执行Ajax调用。 那么有人可以提出建议吗?

此致

2 个答案:

答案 0 :(得分:1)

您的if语句错误:

if (data.IsSuccess = true)

它应该是:

if (data.IsSuccess == true)

答案 1 :(得分:1)

您使用“=”代替“==”进行比较 addserver()方法

使用如下

if (data.IsSuccess == true)

或简单

    if (data.IsSuccess)