好吧,現在我正在嘗試學習.net core mcv,並且我有一個將數據從MySQL映射回我的表單的問題。當我使用單個按鈕將表單作爲單個文本框以及表單之外的其他字段(但在同一頁上)時,映射工作正常。如果我包含表單中的所有字段,則會獲取數據,但不會顯示在頁面上。我甚至已經將多個提交按鈕之一編碼爲數據的更新。我使用第一個文本框從數據庫中獲取項目(它不會映射到文本框),然後在第二個文本框(應該有現有數據但是爲空)中放入要在數據庫中更新的信息,單擊該文本框的提交按鈕,並更新數據庫(但視圖中的文本框保持空白)。Multibutton form不會將數據映射回文本框.net core 1.1
我的模型:
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; }
}
}
我的控制器:
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.
映射工作,但只有表單的第一個字段和按鈕工作。使用圍繞所有四個字段和按鈕的表單,映射不起作用,但第二個按鈕的編碼DOES會在單擊Button2時更新數據庫。
有人可以解釋我在這裏做錯了嗎?
謝謝!