簡體   English   中英

如何獲取“的值”<select></select> ” 從視圖到控制器的“ActionResult”?

[英]How to get the value of "<select></select>" from a view into a Controller's "ActionResult"?

我有一個標簽和一個按鈕。 單擊按鈕時,將調用控制器中的 actionResult。 像這樣。

<button type="button" onclick="location.href='@Url.Action("GetAllItems", "Items")'">Get Items</button>

這是ActionResult

public ActionResult GetAllItems() {
        string selectedItem = string.Empty;
        ItemsRepository itemsRepository = new ItemsRepository();
        ModelState.Clear();
        return View(itemsRepository.GetAllItems());
    }

selectedItem是我想要存儲 selectedText 或 selectedValue 的變量。 但我不知道該怎么做。

這是<Select>標簽。

<select style="width:170px" id="ItemsID" name="Items"></select>

這是從onChange事件獲得不同結果的粗略函數。

<script>
$(document).ready(function () {
    $("#ItemsID").change(function () {
        var a = $('#ItemsID option:selected').val();
        var b = $('#ItemsID option:selected').text().trim();
        var c = $('#ItemsID option:selected').index();

        alert(a);
        alert(b);
        alert(c);
    })
});

請幫忙。

location.href 不發送 POST 請求。 你要做的是在你的 ActionResult 中放置一個表單標簽來發出一個 POST 請求。

<form action='yourAction'>
<select name='name'></select>
<button type="submit">Get Items</button>
</form>

您可以使用以下代碼在操作方法中獲取您選擇的值。 請注意,您必須將 html select 元素的name屬性傳遞給 Request。

var selectedValue = Request["Items"];

此外,請確保單擊的按鈕使用如下代碼提交表單。

要點是您只能使用 Request 對象來訪問 C# 代碼中的 html 元素值,前提是 html 元素和提交按鈕在同一個表單中。 如果您使用重定向用戶而不是提交表單的按鈕,那么這將不起作用,因此它必須是提交類型按鈕,如下面的代碼所示。

@using (Html.BeginForm("YourActionName", "ControllerName")) {

          <select style="width:170px" id="ItemsID" name="Items"></select>

          <input type="submit" value="Submit Data" id="btnSubmit" />

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM