[英]Angular & ASP.NET MVC - Parameter is null when I pass a parameter to my backend Controller
If you look at the parameter of my ASP.NET MVC Controller clientId, it's always null. 如果您查看我的ASP.NET MVC控制器clientId的参数,则该参数始终为null。
the only way i can get it to not be null and actually pass the data through successfully is to create a class... but that gets tedious and I can't create a class for every backend function i make just to get this to work. 我不能使它不为null并成功地成功传递数据的唯一方法是创建一个类...但是这很乏味,我不能为我制作的每个后端函数都创建一个类,只是为了使其正常工作。
Is there a way to pass data successfully without creating a class? 有没有一种方法可以成功地传递数据而无需创建类?
Thank you for any help 感谢您的任何帮助
Angular Factory 角工厂
PlaylistsFactory.getUsersForClient = function (clientId) {
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: JSON.stringify(clientId)
});
};
Angular Controller 角度控制器
PlaylistsFactory.getUsersForClient(clientId)
.success(function (userList) {
console.log('success!');
});
ASP.NET MVC Controller ASP.NET MVC控制器
public JsonResult GetUsersForClient(string clientId) //clientId is always null unless i create an object
{
...
}
Try making your JSON parameter match the name of your C# parameter as well as encasing that in the data payload as JSON: 尝试使JSON参数与C#参数的名称匹配,并将其作为JSON封装在数据有效载荷中:
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: {clientId: JSON.stringify(clientId)}
});
};
i would recommend that you follow the rules of a RESTful API. 我建议您遵循RESTful API的规则。
This means you should use the HTTP verbs like GET (getting data), POST (updating data), PUT (creating data), DELETE (deleting data). 这意味着您应该使用HTTP动词,例如GET(获取数据),POST(更新数据),PUT(创建数据),DELETE(删除数据)。 See http://www.tutorialsteacher.com/mvc/actionverbs-in-mvc
参见http://www.tutorialsteacher.com/mvc/actionverbs-in-mvc
Then you could also add the parameter you want to pass into the route of your API: /Show/GetUsersForClient/{clientId}
. 然后,您还可以将要传递的参数添加到API的路由中:
/Show/GetUsersForClient/{clientId}
。 See http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx 参见http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
In this case you disengage the problem of sending data in the body without having a ViewModel on the MVC-Controller side. 在这种情况下,您可以解决在主体中发送数据而不在MVC控制器端具有ViewModel的问题。
When you want to proceed with your solution, then try creating the Object before sending it: 如果要继续解决方案,请尝试在发送对象之前创建对象:
PlaylistsFactory.getUsersForClient = function (clientId) {
var payload = { clientId: clientId }
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: payload
});
};
MVC / WebAPI also sometime choke when the content-type in the request header is text/plain or application/json. 当请求标头中的内容类型为text / plain或application / json时,MVC / WebAPI有时也会阻塞。 For example: a json-object will not be recognized properly by .Net when sent in text/plain.
例如:当以文本/纯文本形式发送时,.Net将无法正确识别json对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.