【问题标题】:Binding submit button in view to action result method in Controller将视图中的提交按钮绑定到控制器中的操作结果方法
【发布时间】:2016-08-23 13:12:55
【问题描述】:

我对 ASP.NET 和 MVC 比较陌生(我通常在 winforms/wpf 中工作),我正在尝试自学基础知识。我正在尝试创建一个简单的待办事项列表样式的东西,您可以在其中输入一行文本到文本框中单击添加按钮,然后在下面填充一个列表。

这是我的视图 (Index.cshtml),它位于 Views>ToDo 文件夹中:

@{
ViewBag.Title = "Index";
}
@model List<Models.ToDoListItem>
<h2>To Do List</h2>

<form asp-action="Create" asp-controller="ToDo" asp-method="post">
    <div>
        <input name="ToDoItem"/>
        <input type="submit" value="Add Task"/>
    </div>
</form>

<div>
    <ul>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
                <li>
                    <label>@item.ItemText</label>
                </li>
            }
        }

    </ul>
</div> 

这是我的控制器 ToDoController.cs,它位于 Controllers 文件夹中

public class ToDoController : Controller
{
    // GET: ToDo
    public ActionResult Index()
    {
        return View(Models.ToDoListItem.GetAll());
    }

    [HttpPost] //This was added as suggested in comments and answers
    public ActionResult Create(string toDoItem)
    {
        Models.ToDoListItem.Create(toDoItem);
        return RedirectToAction("Index");
    }
}

现在根据我的阅读,将操作Create 添加到我的表单标签的ToDocontroller 部分应该会将我的提交按钮点击映射到我的ActionResult 类中的“创建”ActionResult 方法。

当我在 create 方法上使用断点运行我的代码时,单击提交按钮不会击中断点,并且不会将任何内容添加到列表中。

如果有人知道我哪里出错了,我们将不胜感激。

谢谢。

【问题讨论】:

  • [HttpPost] 放在Create 方法上。
  • 您是 Asp.NET MVC 的新手,您开始使用 MVC-6 进行编码。兄弟尝试先从低版本学习。我的建议是从 MVC- 4 开始..
  • @mmushtaq 不,他不应该。他开始的地方很好。
  • 进行 ajax 调用,将解决您的问题。 :)
  • @Berkay 说了什么。表单的默认方法是 POST,您没有响应帖子的操作。如果你将method="get" 添加到你的表单标签中,它会起作用,但它实际上应该是一个 POST,因为它是非幂等的。

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


【解决方案1】:

首先,您发布的 HTML 用于您的 Index 视图,它对应于您的 public ActionResult Index() 方法。

其次,为了让您的提交按钮起作用,您需要在控制器中使用HttpPost ActionResult Create 方法。您发布的是HttpGet ActionResult Create 方法。

类似的东西:

/*public ActionResult Create()
{
    return View();
}*/

// the code above is only necessary if you decide to create your own separate Create View

[HttpPost]
public ActionResult Create(string toDoItem)
{               
    Models.ToDoListItem.Create(toDoItem);
    return RedirectToAction("Index");
}

如果这有帮助,请告诉我。

【讨论】:

  • “你需要创建一个创建视图”——不,他不需要。
  • @Igor 从我的回答中删除了这个
  • 他也不需要你的代码中的第一个Create
  • 那么你的答案归结为问题下的第一条评论。
  • @mattisrowe 您是否尝试过将剃刀样式用于表单? @Html.BeginForm()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多