开发者

ASP.net MVC put complex data (array) to controller method

I'm porting an ASP.net Web Forms application to MVC.

The application uses AJAX, by means of Ajax-enabled WCF Web service and asp:ScriptManager. I send an array of objects for service, it handles it just great. Code example,

    <script type="text/javascript">
    $().ready(function () {
        var ser = new Services.TasksService();
        $('#tasks').tasksgrid(
            'newTaskName',
            'createTask',
            'submitData',
            loadData,
            submitData,
            deleteData
        );

        function loadData(callback) {
            return ser.GetAllTasks(callback, null, null);
        }

        function submitData(data, callback) {
            return ser.Submit(data, callback, null, null);
        }

        function deleteData(data, callback) {
            return ser.Delete(data, callback, null, null);
        }
    }
    );

</script>

WCF service side code:

    [ServiceContract(Namespace = "Services")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TasksService
{
    [OperationContract]
    public IList<Task> GetAllTasks()
    {
        //Code..
    }

    [OperationContract]
    public void开发者_如何学编程 Submit(IList<Task> tasks)
    {
        //Code..
    }

    [OperationContract]
    public void Delete(IList<Task> tasks)
    {
        //Code..
    }
}

The Submit/Delete method, recieves Array of Tasks objects. I create those array dynamically in client side script and just put it to corresponding Services.TasksService (no $.toJSON or JSON.stringly call, nothing like that). WCF infrastucture handles it greacefully and I always get a correct object on server.

Now, I'm getting rid of WCF service and try to do the same with Controller class. GetAllTasks were fine.. but I totally missed with 'recieving' data methods.

In controller I have,

        [HttpPost]
    public JsonResult Submit(IList<Task> tasks)
    {

On client,

            function submitData(data, callback) {
            $.post('/Tasks/Submit', JSON.stringify(data), callback, 'json');
        }

But anything I tried, I always recieve null as tasks object (so, data is not binded).

I've seen Phil Haack post on that, but would like to avoid using of any additional assemblies, if possible.


MVC needs to be told what variable on the server side to bind the data to. In your example you could do the following:

    function submitData(data, callback) {
    $.post('/Tasks/Submit', { tasks: data }, callback, 'json');
}


Look here http://theycallmemrjames.blogspot.com/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜