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

时间:2015-10-16 18:22:49

标签: 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; }

然后我有一个带文本框和提交按钮的简单视图:

@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,它返回正常,但现在我添加了模型,它不会返回任何东西。

3 个答案:

答案 0 :(得分:2)

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

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

如果是我,我会将其设为HttpPost或为此表单创建单独的操作,这样我就不会在网址中看到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();
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这里有几件事情要发生。首先,您要分割Get和Post操作。表格也只与POST一起使用。您也不需要为动作或控制器命名,除非您将帖子发送到不同的控制器或操作然后GET。

这是得到的。它在页面上呈现表单。你不需要在那里放置[HttpGet],这是默认设置。

    [HttpPost]
    public ActionResult Inquiry(Search search)
    {
        if (!ModelState.IsValid)
        {
            return View(search);
        }

        //so something with your posted model.
    }

以下是将表单发回服务器。模型绑定器将使用您的视图模型连接html表单字段。由于您在视图模型上有验证器,因此您需要检查模型状态是否有效并重新显示具有相关错误的视图。您需要在视图中添加@ Html.ValidationMessageFor(...),以便实际看到这些错误。

# First digital input address
address = 40003
# Written value
value = 255

# It will send '11111111' to the output 
client.write_register(address, value)