C# 获取从文本框传递到控制器的变量
我有一个简单的模型,用于搜索页面进行验证:C# 获取从文本框传递到控制器的变量,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我有一个简单的模型,用于搜索页面进行验证: public class Search { [Required] [DisplayName("Tag Number")] [RegularExpression("([1-9][0-9]*)", ErrorMessage = "Tag must be a number")] public int HouseTag { get; set; } 然后,我有一个带有文本框和提交按
public class Search {
[Required]
[DisplayName("Tag Number")]
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Tag must be a number")]
public int HouseTag { get; set; }
然后,我有一个带有文本框和提交按钮的简单视图:
@model Search
@{
Layout = "~/_Layout.cshtml";
}
@using (Html.BeginForm("Search", "Inquiry", FormMethod.Get)){
@Html.LabelFor(m =>m.HouseTag)
@Html.TextBoxFor(m=>m.HouseTag, new { type = "Search", autofocus = "true", style = "width: 200px", @maxlength = "6" })
<input type="submit" value="Search" id="submit"/>
当我用一个数字执行它时,我得到一个传递给控制器的空值,这会导致事情发生爆炸。我使用该模型来控制搜索框的一些属性以进行验证。我以前只有@Html.TextBox,它返回的很好,但现在我添加了模型,它不返回任何内容。您需要一个名为id的参数,并将HouseTag作为该参数的名称传递。您应该在搜索方法中将id重命名为HouseTag。您可以将参数设置为搜索类型,然后在操作中访问属性
[HttpGet]
public ActionResult Search(Search model){
ViewBag.Tag = model.HouseTag;
return View();
}
如果是我,我会将此设置为HttpPost或为此表单创建单独的操作,这样我就不会在URL中看到HouseTag文本
@using (Html.BeginForm("Search", "Inquiry", FormMethod.Post))
{
@Html.LabelFor(m => m.HouseTag)
@Html.TextBoxFor(m => m.HouseTag, new { type = "Search", autofocus = "true", style = "width: 200px", @maxlength = "6" })
<input type="submit" value="Search" id="submit" />
}
[HttpPost]
public ActionResult Search(Search model){
ViewBag.Tag = model.HouseTag;
return View();
}
@使用(Html.BeginForm(“搜索”、“查询”、FormMethod.Post))
{
@LabelFor(m=>m.HouseTag)
@Html.TextBoxFor(m=>m.HouseTag,新的{type=“Search”,autofocus=“true”,style=“width:200px”,@maxlength=“6”})
}
[HttpPost]
公共行动结果搜索(搜索模型){
ViewBag.Tag=model.HouseTag;
返回视图();
}
这里发生了一些事情。首先,您需要拆分Get和Post操作。此外,表格仅与邮局的表格一起使用。您也不需要命名您的操作或控制器,除非您将帖子发送到另一个控制器或操作,然后发送GET
这是最重要的。它在页面上呈现表单。您不需要在那里放置[HttpGet],这是默认设置
public ActionResult Search()
{
return View();
}
下面将把表单发回服务器。模型绑定器将把html表单字段与视图模型连接起来。由于视图模型上有验证器,因此需要检查模型状态是否有效,并重新显示包含相关错误的视图。您需要将@Html.ValidationMessageFor(…)添加到视图中,以便实际看到这些错误
[HttpPost]
public ActionResult Inquiry(Search search)
{
if (!ModelState.IsValid)
{
return View(search);
}
//so something with your posted model.
}
[HttpPost]
public ActionResult Inquiry(Search search)
{
if (!ModelState.IsValid)
{
return View(search);
}
//so something with your posted model.
}