在我的控制器中,我采取了行动:
[HttpGet]
public ActionResult CreateAdmin(object routeValues = null)
{
//some code
return View();
}
和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,
});
}
http get Action
中的变量routeValues始终为空。如何将对象作为参数正确传递给[http get] Action
?
答案 0 :(得分:10)
您无法将对象传递给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();
}
然后,您可以从应用的任何位置传递值,例如:
http://someurl.com/CreateAdmin?valu1=1&value2="hello"&value3="world"
答案 1 :(得分:3)
如前所述,您无法将整个对象传递给HTTPGET Action。但是,当我不想拥有包含数百个参数的Action时,我喜欢做的是:
因此,假设您有此类代表您的所有输入字段:
public class AdminContract
{
public string email {get;set;}
public string nameF {get;set;}
public string nameL {get;set;}
public string nameM {get;set;}
}
然后,您可以添加一个只需要一个字符串参数的GET Action:
[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);
}
tada!只需通过字符串化和对象(在前端)然后转换它(在后端),您仍然可以在请求中传递整个对象而不是使用数十个参数时享受HTTPGET请求的好处。
答案 2 :(得分:0)
您可以将值传递给Http Get方法,例如
Html.Action("ActionName","ControllerName",new {para1=value, para2 = value});
您可以在控制器中定义您的操作,例如
[HtttpGet]
public ActionResult ActionName(Para1Type para1, Para2Type para2)
{
}