Skip to main content
 首页 » 编程设计

c#之使用 ASP MVC 将字符串从 form> 传递到 Controller

2024年02月23日26jpfss

我正在做这个小教程:http://www.asp.net/mvc/videos/mvc-2/how-do-i/creating-a-tasklist-application-with-aspnet-mvc

但不知何故,他正在将一个字符串传回 Controller 。但我无法让我的传回一个字符串。我错过了什么?

创建.aspx

<form method="post" action="/Home/CreateNew"> 
    <label for="task">Task:</label> 
    <input type="text" name="task" /> 
    <input type="submit" value="Add Task" />  
</form> 

HomeController.cs

public ActionResult CreateNew(object obj ) // <-- expecting a string but getting an object. 
{ 
  string whattype = obj.GetType().ToString(); //just an obj, expecting a string 
  //add to DB next 
} 

请您参考如下方法:

MVC 是基于约定的 - 表单元素名称是 task 所以它应该是参数名称:

public ActionResult CreateNew(string task ) //<-- expecting a string but getting an object. 
{ 
  string whattype = obj.GetType().ToString(); //just an obj, expecting a string 
  //add to DB next 
}