好的,现在我正在尝试学习 .net core mcv,但在将数据从 MySQL 映射回我的表单时遇到问题。当我将表单制作为带有单个按钮的单个文本框以及表单外部的其他字段(但在同一页面上)时,映射工作正常。如果我包含表单中的所有字段,则会获取数据但不会显示在页面上。我什至编写了多个提交按钮之一作为数据更新。我使用第一个文本框从数据库中获取项目,它确实做到了(但没有映射到文本框),然后在第二个文本框(应该有现有数据,但为空)中我输入了数据库中要更新的信息,单击该文本框的提交按钮,数据库就会更新(但 View 中的文本框保持空白)。
我的模型:
using System;
namespace DbTest.Models
{
public class ProductInventory
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public int Field4 { get; set; }
}
}
我的 Controller :
using System;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using Microsoft.AspNetCore.Authorization;
using DbTest.Models;
namespace DbTest.Controllers
{
public class InventoryController : Controller
{
// [Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult ProcessForm(string button, ProductInventory p)
{
IActionResult toDo = null;
if (button == "Button1")
{
toDo = GetItem(p);
}
if (button == "Button2")
{
toDo = UpdateField2(p);
}
if (button == "Button3")
{
toDo = UpdateField3(p);
}
if (button == "Button4")
{
toDo = UpdateField4(p);
}
return toDo;
}
// [HttpPost]
public IActionResult GetItem(ProductInventory p)
{
//CODE SNIP - DATABASE QUERY, IT ALL WORKS, SO WHY BOTHER YOU WITH THE DETAILS?
return View("Index", p);
}
public IActionResult UpdateField2(ProductInventory p)
{
//CODE SNIP - DATABASE UPDATE, ALL WORKS, NOTHING TO SEE HERE
return View("Index", p);
}
}
}
最后,我的观点:
@model DbTest.Models.ProductInventory
@{
ViewData["Title"] = "Inventory Page";
}
@using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
@Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
<div>
Field 2:
@Html.TextBoxFor(model => model.Field2)
<input type="submit" name="button" value="Button2" />
</div>
<div>
Field 3:
@Html.TextBoxFor(model => model.Field3)
<input type="submit" name="button" value="Button3" />
</div>
<div>
Field 4:
@Html.TextBoxFor(model => model.Field4)
<input type="submit" name="button" value="Button4" />
</div>
}
重申一下,如果我在 Button1 之后关闭表单:
@using (Html.BeginForm("ProcessForm", "Inventory", FormMethod.Post))
{
<div>
Search Item (Field 1):
@Html.TextBoxFor(model => model.Field1)
<input type="submit" name="button" value="Button1" />
</div>
}
<div>
Field 2:
//etc.
映射有效,但只有表单的第一个字段和按钮有效。对于所有四个字段和按钮周围的表单,映射不起作用,但第二个按钮的编码确实会在单击 Button2 时更新数据库。
有人可以解释一下我在这里做错了什么吗?
谢谢!
最佳答案
首先,不要在 ASP.NET Core 中使用 html 帮助程序。它们可以工作,但不是最佳实践。而是使用 tag helpers只要有可能。此外,不要将数据库模型用作 View 模型。
关于您的 Index
操作:您忘记将 View 模型传递给您的 View 。
在您的 ProcessForm
操作中,您实例化 IActionResult
,然后为其分配一个(操作)函数。不要那样做。请改用 return RedirectToAction("ActionName");
。
在您的情况下,我将在 ProcessForm
操作或函数中处理数据库更新,该操作不会返回 IActionResult
。
总之,我只能建议您阅读 ASP.NET Core 文档,然后再次询问是否仍然无法正常工作。我建议您从阅读 this 开始.
关于mysql - 多按钮表单不会将数据映射回文本框.net core 1.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44580616/