簡體   English   中英

mvc Html.BeginForm 不同的 URL 模式

[英]mvc Html.BeginForm different URL schema

我正在為 DropDown 創建一個表單,如下所示:

@{
    Html.BeginForm("View", "Stations", FormMethod.Get);
}
@Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
@{
    Html.EndForm();
}

如果我從下拉列表中選擇一個值,我會被重定向到正確的控制器,但 URL 不是我想要的:

/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c

我想要的是:

/站/視圖/f2cecc62-7c8c-498d-b6b6-60d48a862c1c

那么如何將 id= querystring 參數替換為我想要的更簡單的 URL Scheme 呢?

帶有FormMethod.Get的表單將始終將其表單控件的值作為查詢字符串值回發。 瀏覽器無法根據您的路由配置生成 url,因為它們是服務器端代碼。

如果你真的想生成/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c ,那么你可以使用 javascript/jquery 來構建你自己的 url 並重定向

@using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
    @Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}

var baseUrl = '@Url.Action("View", "Stations")';
$('#id').change(function() {
    location.href = baseUrl + '/' $(this).val();
});

旁注:在.change()事件上提交不是預期的行為,會讓用戶感到困惑。 建議您添加一個按鈕讓用戶進行選擇,檢查它然后提交表單(處理按鈕的.click()事件而不是下拉列表的.change()事件)

刪除“ id

@Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

暫無
暫無

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

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