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

标签 c# asp.net asp.net-mvc-2

我正在做这个小教程: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
}

关于c# - 使用 ASP MVC 将字符串从 <form> 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8554628/

相关文章:

javascript - 仅显示 javascript 对象的对象属性

asp.net - 强制页面将自身加载到另一个页面的 iframe 中

c# - 如何覆盖路由表中的 .svc 文件?

c# - 如何正确连接到 Json.NET 的 JObject.ToObject<T>()?

c# - 如果 C# 规范将它们称为简单类型,为什么 Type 类有一个名为 IsPrimitive() 的方法?

c# - Azure ASP .net WebApp - 500 错误 - 请求超时

wcf - 为什么在构建 RESTful api 时要使用 WCF 而不是 MVC?

asp.net - RenderAction 在当前区域的当前 Controller 中找不到操作方法

c# - Nancy decimal 属性绑定(bind)不起作用

c# - 没有 'Access-Control-Allow-Origin' header 存在 Angular 6 与 Asp.net Core 2.1