在您的視圖代碼中,你是不是設置option
的value
屬性。所以$('#othercatches').val()
會給你undefined。
使用DropDownList
/DropDownListFor
HTML幫助器方法呈現SELECT元素。
使用強類型視圖。例如:如果你的觀點是創建DDL,您將定義一個視圖模型這樣
public class ClientDDL
{
public string Name { set;get;}
public int SelectedCatch { set;get;}
public IEnumerable<SelectListItem> OtherCatches { set;get;}
//Other relevant proeprties also here
public ClientDDL()
{
//Lets initialize the OtherCatches Proeprty
OtherCatches=new List<SelectListItem>();
}
}
現在我們GET
行動,我們將創建這個視圖模型的對象,發送到視圖。現在
public ActionResult CreateDDL()
{
ClientDDL ddl new ClientDDL();
// The below line is hard coded for demo. you may replace
// this with loading data from your Data access layer.
ddl.OtherCatches= new[]
{
new SelectListItem { Value = "1", Text = "Book" },
new SelectListItem { Value = "2", Text = "Pen" },
new SelectListItem { Value = "3", Text = "Computer" }
};
return View(ddl);
}
我們認爲(CreateDDL.cshtml
),這是強類型我們ClientDDL
類看起來像這樣
@model ClientDDL
@using(Html.Beginform())
{
@Html.DropDownListFor(x => x.SelectedCatch,
new SelectList(Model.OtherCatches,"Value","Text"), "Select..")
}
<script type="text/javascript">
$(function(){
$("#SelectedCatch").change(function(){
$.ajax({
url: "@Url.Action("DDL","Clients")",
type: "POST",
data: { name: $(this).val() },
success: function (result) {
alert(result)
}
});
});
});
</script>
決不硬編碼路徑,這樣的操作方法。儘可能使用URL Helper方法。
不確定爲什麼你有一個virtual
方法?它應該很簡單,因爲這
[HttpPost]
public ActionResult DDL(int name)
{
//do method here
}
感謝上例的示例代碼我的朋友 –