簡體   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