[英]ASP.net MVC put complex data (array) to controller method
I'm porting an ASP.net Web Forms application to MVC. 我正在将ASP.net Web窗体应用程序移植到MVC。
The application uses AJAX, by means of Ajax-enabled WCF Web service
and asp:ScriptManager
. 该应用程序通过
Ajax-enabled WCF Web service
和asp:ScriptManager
使用AJAX。 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: WCF服务端代码:
[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. Submit / Delete方法接收Array of Tasks对象。 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). 我在客户端脚本中动态创建了这些数组,然后将其放到相应的
Services.TasksService
(没有$ .toJSON或JSON.stringly调用,没有类似的东西)。 WCF infrastucture handles it greacefully and I always get a correct object on server. WCF基础结构很好地处理了这个问题,我总是在服务器上得到一个正确的对象。
Now, I'm getting rid of WCF service and try to do the same with Controller class. 现在,我摆脱了WCF服务,并尝试对Controller类执行相同的操作。 GetAllTasks were fine.. but I totally missed with 'recieving' data methods.
GetAllTasks很好..但是我完全错过了“接收”数据方法。
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). 但是,无论我尝试什么,我总是将null作为任务对象接收(因此,数据未绑定)。
I've seen Phil Haack post on that, but would like to avoid using of any additional assemblies, if possible. 我已经看过Phil Haack的文章 ,但是如果可能的话,希望避免使用任何其他程序集。
MVC needs to be told what variable on the server side to bind the data to. 需要告知MVC服务器端将数据绑定到哪个变量。 In your example you could do the following:
在您的示例中,您可以执行以下操作:
function submitData(data, callback) {
$.post('/Tasks/Submit', { tasks: data }, callback, 'json');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.