繁体   English   中英

从文本框中获取传递给我的控制器的变量

[英]get a variable passed to my controller from a textbox

我有一个用于搜索页面的简单模型来进行一些验证:

        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"/>

我的控制器期望一个id参数:

    [HttpGet]
    public ActionResult Search(int id){
        ViewBag.Tag = id;
        return View();
    }

当我用数字执行它时,我将一个空值传递给控制器​​,从而导致事情崩溃。 我正在使用模型来控制搜索框的某些属性以进行验证。 我曾经只有@ Html.TextBox,它返回的很好,但是现在我已经添加了模型,它不会返回任何东西。

您可以将参数设置为“搜索”类型,然后在操作中访问该属性

[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();
}

您期望使用一个名为id的参数,并将HouseTag作为该参数的名称传递,您应该在Search方法中将id重命名为houseTag。

这里发生了几件事。 首先,您将要拆分Get和Post操作。 表格也只能与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.
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM