У меня есть dropdownbox, который заполняется данными из базы данных. Если я выберу элемент в раскрывающемся списке, я хочу использовать значение в методе GetValueSelected() в моем контроллере. На данный момент я не могу получить эту ценность в методе GetValueSelected. Как я могу написать это так, чтобы получить эту ценность и использовать ее для другой обработки.
@model PopulateDropDownList.Models.Populate
@using PopulateDropDownList.Models
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {rnctype = "multipart/form-data" }))
{
<p>
@Html.DropDownList("mylist", Helper.GetDescription(),"--select here--")
<input id="Button1" type="button" value="button" />
</p>
}
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {
var SelCat = $("#mylist").val();
if (SelCat != 0) {
var url = '@Url.Action("GetValueSelected", "Home")';
$.post(url, { Id: SelCat },
function (data) {
});
}
else {
alert("You need to select an item");
}
});
});
</script>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public void GetValueSelected()
{
string getSelectedValue = Request.Form["mylist"];
}
}
попробуй это:
CSHTML:
@*rnctype -> enctype*@
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {enctype = "multipart/form-data" }))
{
<input type="hidden" id="urlGetValueSelected" value="@Url.Action("GetValueSelected", "Home")" />
<p>
@Html.DropDownList("mylist", Helper.GetDescription(),"--select here--")
<input id="Button1" type="button" value="button" />
</p>
}
JS:
$(document).ready(function () {
$("#Button1").click(function (event) {
event.preventDefault();
var selCat = $("#mylist").val();
if (selCat.length != 0) { // check the value if that is correct to empty option
$.post($('#urlGetValueSelected').val(), { id: SelCat }, function (data) {
alert(data.message);
});
}
else {
alert("You need to select an item");
}
});
});
контроллер:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetValueSelected(string id)
{
string getSelectedValue = id;
return Json(new { Message = string.Format("id: {0}", id) });
}
}