2012-08-06 87 views
0

我想從我的剃鬚刀視圖提交一個ajax窗體,並且我希望控制器返回一個JSON對象。當我使用(「#form0」)。submit(alert(「hi」););數據發送到控制器,我收到警報。但是,當我使用(「#form0」)。submit(function(){alert(「hi」);});數據沒有通過,我也沒有收到警報。我覺得這是我的語法輕微,我錯過了。下面是相關的代碼:無法重載提交方法的Ajax.BeginForm

的jQuery:

$(function() { 
//setting up the schedule modal dialoag. 
$("#schedModal").dialog({ 
    buttons: { 
     Submit: 
       function() { 
        $("#form0").ajaxSubmit(function() { 
         //this is where I want to put the magic, but I need the alert to fire first. 
         alert("hi"); 
         return false; 
        }); 
       }, 
     Cancel: 
       function() { 
        $(this).dialog("close"); 
       } 
    }, 
    autoOpen: false, 
    minHeight: 350, 
    modal: true, 
    resizable: false 
}); 

有針對性的觀點:

@model FSDS.DataModels.Schedule 

@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { UpdateTargetId = "partial" }, new {})) 
{ 
@Html.ValidationSummary(true) 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.ScheduleName) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.ScheduleName) 
     @Html.ValidationMessageFor(model => model.ScheduleName) 
    </div> 

    @* tons of other labels and editor fields go in here, omitted for brevity. *@ 
} 

控制器,如果該事項:

[HttpPost] 
    public ActionResult scheduleNew(Schedule schedule) 
    { 
     if (Request.HttpMethod == "POST") 
     { 
      FSDSDBEntities context = new FSDSDBEntities(); 

      if (ModelState.IsValid) 
      { 
       context.Schedules.AddObject(schedule); 
       context.SaveChanges(); 
      } 

      return Json(schedule); 
     } 
     else 
     { 
      return PartialView(); 
     } 
    } 

回答

2

只需使用$('#form0').submit();

Submit: function() { 
    $('#form0').submit(); 
} 

然後定義你給ajaxForm一個OnSuccess處理程序時AJAX請求成功,將調用:

@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { OnSuccess = "success", UpdateTargetId = "partial" }, new {})) 

最後success JavaScript處理:

function success(data) { 
    // the form was successfully submitted using an AJAX call. 
    // here you could test whether the data parameter 
    // represents a JSON object or a partial view 
    if (data.ScheduleName) { 
     // the controller action returned the schedule JSON object 
     // => act accordingly 
    } else { 
     // the controller action returned a partial view 
     // => act accordingly 
    } 
} 
+0

工程就像一個夢。你是一個紳士和學者,Darin Dimitrov。 – Billdr 2012-08-06 17:05:53