我正在尝试使用ASP.NET MVC来获取用户输入Html.BeginForm()
并在同一页面/视图上显示用户输入的内容。我遇到的问题是用户点击提交后,数据不显示。
这是我的项目的设置方式,在中Index.cshtml
:
@model SynNetTest.Models.HomeModel
@{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="text-center"
<h2>The current directory: @Model.directory</h2>
<h3>@Model.Load()</h3>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Word Details</th>
</tr>
<tr>
<td>Enter Word: </td>
<td>
@Html.TextBoxFor(m => m.word)
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
<h4>The word entered: @Model.word</h4>
</div>
在HomeModel.cs
:
public class HomeModel
{
public string directory { get; set; }
public WordNetEngine wordNet { get; set; }
public string word { get; set; }
public List<SynSet> synSetList { get; set; }
//load words to access
public string Load()
{
wordNet.AddDataSource(new StreamReader(Path.Combine(directory, "data.adj")), PartOfSpeech.Adjective);
wordNet.Load();
return "Database Loaded Successfully";
}
}
在HomeController.cs
:
public class HomeController : Controller
{
public IActionResult Index()
{
var home = new HomeModel()
{
directory = Directory.GetCurrentDirectory(),
wordNet = new WordNetEngine(),
};
return View(home);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
我正在使用Syn.WordNet NuGet包来尝试获取用户输入以打印出来的单词的定义。到目前为止,我只是试图查看输入是否可以处理并放在同一页面/视图上。
据我了解,您无法使用Home / Index方法查看表单数据。您可以添加以下代码。
[HttpPost]
public IActionResult Index(HomeModel homeModel)
{
}
当用户单击“提交”按钮时,它将与HomeModel绑定所有视图字段详细信息。简而言之,您缺少[HttpPost]和模型绑定的方法。
您也可以使用FromForm属性获取单个字段数据。希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句