runat="server"
とasp:XXX
ウェブコントロールのフォームを使用しています。これらの概念は、ASP.NET MVCで使用されるべきではありません。これらのサーバーコントロールが依存するViewStateとPostBacksはもうありません。
だから、ASP.NET MVCであなたは、データを表すビューモデルを定義することから始めます:
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
、あなたは二つの動作(ビューをレンダリング1、別のハンドル付きのコントローラを定義しますフォーム送信):
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ItemsViewModel
{
Items = new[]
{
new SelectListItem { Value = "Theory", Text = "Theory" },
new SelectListItem { Value = "Appliance", Text = "Appliance" },
new SelectListItem { Value = "Lab", Text = "Lab" }
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ItemsViewModel model)
{
// this action will be invoked when the form is submitted and
// model.SelectedItemId will contain the selected value
...
}
}
、最終的にあなたが対応する強く型付けされたIndex
ビュー記述します。
を
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.ItemsViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text")) %>
<input type="submit" value="OK" />
<% } %>
</asp:Content>
これはまた、あなたのビュー内の選択この(これは私はお勧めしませんものですが)ハードコーディングすることができ言われている:
<% using (Html.BeginForm()) { %>
<select name="selectedItem">
<option value="Theory">Theory</option>
<option value="Appliance">Appliance</option>
<option value="Lab">Lab</option>
</select>
<input type="submit" value="OK" />
<% } %>
をして、次のコントローラがありますどのように
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string selectedItem)
{
// this action will be invoked when the form is submitted and
// selectedItem will contain the selected value
...
}
}
を私はこのコードを使用するvar model = new ItemsViewModel { Items = new [] { new SelectListItem {Value = "Theory"、Text = "Theory"}、 new Select 新しいSelectListItem {Value = "Lab"、Text = "Lab"} } }; ListItem {Value = "Appliance"、Text = "Appliance"}私はデータベースからドロップダウンリストの値を取得したい場合。私はどのようなコードを使用するのですか? –
@Pushpendra Kuntalは、使用しているデータベースの種類、データベーステーブルのスキーマの外観、使用しているデータベースアクセステクノロジの種類によって異なります。 –