Yur*_*rov 7 asp.net asp.net-mvc
在我的控制器中我采取了行动:
[HttpGet]
public ActionResult CreateAdmin(object routeValues = null)
{
//some code
return View();
}
Run Code Online (Sandbox Code Playgroud)
和http帖子:
[HttpPost]
public ActionResult CreateAdmin(
string email,
string nameF,
string nameL,
string nameM)
{
if (email == "" || nameF == "" || nameL == "" || nameM == "")
{
return RedirectToAction("CreateAdmin", new
{
error = true,
email = email,
nameF = nameF,
nameL = nameL,
nameM = nameM,
});
}
Run Code Online (Sandbox Code Playgroud)
变量routeValues in http get Action始终为空.如何正确地将对象作为参数传递给[http get] Action?
ali*_*irz 12
您不能将对象传递给GET,而是尝试传递单个值,如下所示:
[HttpGet]
public ActionResult CreateAdmin(int value1, string value2, string value3)
{
//some code
var obj = new MyObject {property1 = value1; propety2 = value2; property3 = value3};
return View();
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以从应用的任何位置传递值,例如:
http://someurl.com/CreateAdmin?valu1=1&value2="hello"&value3="world"
Run Code Online (Sandbox Code Playgroud)
小智 6
如前所述,您无法将整个对象传递给 HTTPGET 操作。但是,当我不想使用具有数百个参数的操作时,我喜欢做的是:
因此,假设您有一个代表所有输入字段的类:
public class AdminContract
{
public string email {get;set;}
public string nameF {get;set;}
public string nameL {get;set;}
public string nameM {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以添加一个 GET 操作,该操作只需要一个字符串参数:
[HttpGet]
public ActionResult GetAdmin(string jsonData)
{
//Convert your string parameter into your complext object
var model = JsonConvert.DeserializeObject<AdminContract>(jsonData);
//And now do whatever you want with the object
var mail = model.email;
var fullname = model.nameL + " " + model.nameF;
// .. etc. etc.
return Json(fullname, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
还有田田!只需通过字符串化和对象(在前端)然后转换它(在后端),您仍然可以享受 HTTPGET 请求的好处,同时在请求中传递整个对象,而不是使用数十个参数。
| 归档时间: |
|
| 查看次数: |
25479 次 |
| 最近记录: |