2014-01-17 199 views
0

這裏的時候路過模型回服務器在我的.cshtml代碼:做阿賈克斯

@model WebComposite.Models.MyModel 
@using (Html.BeginForm()) 
{ 
     @Html.TextBoxFor(m => m.id) 
     @Html.TextBoxFor(m => m.name) 
} 
@Scripts.Render("~/Scripts/MyScript.js") 

這裏是在MyScript.js代碼:

$('form').submit(function (e) 
{ 
    e.preventDefault(); 
    //normal Ajax (my own custom version as i'm sure every one has one of these:) 
    SimpleAjax("MyAction", function() { alert("Done"); }); 
}); 

和控制器代碼:

[HttpPost] 
public ActionResult MyAction(MyModel model) 
{ 
    //Problem here is model.id and model.name are empty 
} 

有什麼想法? 由於事先

+0

爲什麼不你用 'Ajax.BeginForm()'? – Marthijn

+0

是的,也嘗試過......看起來像大多數同事和海報在這裏贊成自己做AJAX位。無論如何,我找到了一個工作;所以我只是把它放在下面。不過謝謝你;-) – DotNet98

+1

在你的SimpleAjax方法中顯示什麼。也許你沒有在那裏設置數據? – CoffeeCode

回答

0

我身邊快速查看後猜解是相當不錯的簡單(謝謝你jQuery的!!): 只要你序列化的形式擁有的一切,並張貼回來從你的AJAX調用控制器:

$("form").serializeArray(); 

這是我自己的全面實施阿賈克斯來電 有3個功能(你會打電話給SimplAjaxPost(URL,funcDelegate),它會做休息,你

function Ajax(url, dataObj, getOrPost, theContext, theContentType, theDataType, successFuncName, failedFuncName, alwaysFuncName) 
{ 
    //GET or POST: 
    if (getOrPost == null) { getOrPost = 'POST'; } 
    //Header (what we're sending to the server): http://stackoverflow.com/questions/2722750/ajax-datatype 
    if (theContentType == null) { theContentType = 'application/x-www-form-urlencoded; charset=UTF-8'; } 
    //response (what we're expeting in return):http://stackoverflow.com/questions/2722750/ajax-datatype 
    if (theDataType == null) { theDataType = ""; } 
    //exposing "this" to whatever: http://stackoverflow.com/questions/5097191/ajax-context-option 
    if (theContext == null) { theContext = document.body; } 

    var theURL = NoCache(url); 
    $.ajax(
    { 
     url:   theURL, 
     data:   dataObj, 
     type:   getOrPost, 
     contentType: theContentType, 
     dataType:  theDataType, 
     context:  theContext, 
     async:   false, 
     success:  successFuncName, 
     fail:   failedFuncName, 
     always:   alwaysFuncName, 
     complete:  AjaxScripts 
    }); 
} 

function SimpleAjax(url, successFunctionName) 
{ 
    var dataObj = null; 
    Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null) 
} 

function SimpleAjaxPost(url, successFunctionName) 
{ 
    var dataObj = null; 
    if ($("form").length == 1) 
    { 
     dataObj = $("form").serializeArray(); 
    } 
    Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null) 
} 

function NoCache(url) 
{ 
    var t = new Date(); 
    var qps = "?"; 
    if (url.indexOf("?") > 0) 
    { 
     qps = "&"; 
    } 
    return url + qps + t.getYear() + t.getMonth() + t.getDay() + t.getHours() + t.getMinutes() + t.getSeconds() + t.getMilliseconds(); 
}