我正在嘗試按照基本教程使表單正常作業:https : //www.completecsharptutorial.com/asp-net-mvc5/4-ways-to-create-form-in-asp-net-mvc.php
運行第一個示例后,我的代碼嘗試呈現 localhost:5001/form1 而不是示例的 localhost:5001/Home/form1
我假設問題是我的 Starup.cs 路由需要調整。它目前看起來像:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
控制器代碼:
namespace test_ops.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location =
ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId =
Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpPost]
public ActionResult form1(int txtId, string txtName, string chkAddon)
{
ViewBag.Id = txtId;
ViewBag.Name = txtName;
if (chkAddon != null)
ViewBag.Addon = "Selected";
else
ViewBag.Addon = "Not Selected";
return View("Index");
}
}
}
型號代碼:
namespace test_ops.Models
{
public class TestModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Addon { get; set; }
}
}
在 Home/index.cshtml 查看代碼:
<h4 style="color:purple">
<b>ID:</b> @ViewBag.ID <br />
<b>Name:</b> @ViewBag.Name <br />
<b>Addon:</b> @ViewBag.Addon
</h4>
<hr />
<h3><b>Forms: Weakly Typed</b></h3>
<form action="form1" method="post">
<table>
<tr>
<td>Enter ID: </td>
<td><input type="text" name="txtId" /></td>
</tr>
<tr>
<td>Enter Name: </td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Addon: </td>
<td><input type="checkbox" name="chkAddon" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form>
提交表單后,頁面回傳 404:“無法找到此本地主機頁面未找到該網址的網頁:https://localhost:5001/form1 HTTP ERROR 404”
有人可以讓我知道需要更改什么才能使其正常作業嗎?
uj5u.com熱心網友回復:
嘗試將控制器添加到您的表單中
<form action="@Url.Action("form1", "home")" method="post">
...
但使用這種語法而不是形式要好得多
@using (Html.BeginForm("form1", "Home", FormMethod.Post))
{
<table>
<tr>
//...
<tr>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
}
并檢查 View 檔案夾中的檔案 _ViewImports.cshtml。它應該有
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397509.html
標籤:asp.net-mvc asp.net核心 模型视图控制器
下一篇:在Razor中更改日期格式
