Widzę, że używasz formularzy z internetowymi kontrolkami runat="server"
i asp:XXX
. Te pojęcia nie powinny nigdy być używane w ASP.NET MVC. Nie ma już ViewState i PostBacks, na których polegają te elementy sterujące serwera.
Więc w ASP.NET MVC byłoby zacząć od zdefiniowania widoku modelu reprezentująca dane:
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
wtedy można zdefiniować kontroler z dwóch działań (taki, który powoduje, że widok i innym, że uchwyty złożenie formularza):
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
...
}
}
i wreszcie byś napisać odpowiedni silnie wpisany Index
widok:
<%@ 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>
Mówiąc to można również zakodować to wybierz wewnątrz widzenia (choć jest to coś, czego nie polecam):
<% 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" />
<% } %>
i mają następujące Kontroler:
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
...
}
}
Jak można Używam tego kodu var model = new ItemsViewModel { Items = new [] { new SelectListItem {Wartość = "Theory", Text = "Theory"}, new Select ListItem {Value = "Appliance", Text = "Appliance"}, new SelectListItem {Wartość = "Lab", Text = "Lab"} } }; jeśli chcę uzyskać wartości drop droplist z bazy danych. proszę zasugeruj mi, co powinienem zrobić, jeśli biorę wartości z bazy danych, a następnie jaki kod będę używał? –
@Pushpendra Kuntal, która będzie zależeć od używanej bazy danych, jak wygląda schemat tabeli bazy danych i jakiej technologii dostępu do bazy danych używasz. –