Javascript 如何在asp.net Mvc中存储级联列表中的文本值元素?
我对javascript、jquery和ajax非常陌生。所以我有一个模型:Javascript 如何在asp.net Mvc中存储级联列表中的文本值元素?,javascript,c#,jquery,ajax,asp.net-mvc,Javascript,C#,Jquery,Ajax,Asp.net Mvc,我对javascript、jquery和ajax非常陌生。所以我有一个模型: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { get; set; } public string CategoryName { get; set; } }
namespace hiophop.Models
{
public class CarMake
{
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int CategoryID { get; set; }
}
}
}
我从类中创建一个列表,并在向视图传递JSON时将其添加到控制器中:
namespace hiophop.Controllers
{
public class CarController : Controller
{
List<Category> lstCat = new List<Category>()
{
new Category() { CategoryID = 1, CategoryName = "Dairy" },
new Category() { CategoryID = 2, CategoryName = "Meat" },
new Category() { CategoryID = 3, CategoryName = "Vegetable" }
};
List<Product> lstProd = new List<Product>()
{
new Product() { ProductID = 1, ProductName = "Cheese", CategoryID = 1 },
new Product() { ProductID = 2, ProductName = "Milk", CategoryID = 1 },
new Product() { ProductID = 3, ProductName = "Yogurt", CategoryID = 1 },
new Product() { ProductID = 4, ProductName = "Beef", CategoryID = 2 },
new Product() { ProductID = 5, ProductName = "Lamb", CategoryID = 2 },
new Product() { ProductID = 6, ProductName = "Pork", CategoryID = 2 },
new Product() { ProductID = 7, ProductName = "Broccoli", CategoryID = 3 },
new Product() { ProductID = 8, ProductName = "Cabbage", CategoryID = 3 },
new Product() { ProductID = 9, ProductName = "Pepper", CategoryID = 3 }
};
public ActionResult GetCategories()
{
return Json(lstCat, JsonRequestBehavior.AllowGet);
}
public ActionResult GetProducts(int intCatID)
{
var products = lstProd.Where(p => p.CategoryID == intCatID);
return Json(products, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string c ,string p)
{
ViewBag.x ="Product:"+ p;
ViewBag.y = "category" + c;
return View();
}
}
}
namespace hiopop.Controllers
{
公共类控制器:控制器
{
List lstCat=新列表()
{
新类别(){CategoryID=1,CategoryName=“Dairy”},
新类别(){CategoryID=2,CategoryName=“Meat”},
新类别(){CategoryID=3,CategoryName=“vegeture”}
};
List lstProd=新列表()
{
新产品(){ProductID=1,ProductName=“Cheese”,CategoryID=1},
新产品(){ProductID=2,ProductName=“Milk”,CategoryID=1},
新产品(){ProductID=3,ProductName=“酸奶”,类别ID=1},
新产品(){ProductID=4,ProductName=“Beef”,CategoryID=2},
新产品(){ProductID=5,ProductName=“Lamb”,CategoryID=2},
新产品(){ProductID=6,ProductName=“Pork”,CategoryID=2},
新产品(){ProductID=7,ProductName=“Brocoli”,CategoryID=3},
新产品(),
新产品(){ProductID=9,ProductName=“Pepper”,CategoryID=3}
};
公共操作结果GetCategories()
{
返回Json(lstCat,JsonRequestBehavior.AllowGet);
}
公共行动结果GetProducts(int intCatID)
{
var products=lstProd.Where(p=>p.CategoryID==intCatID);
返回Json(products,JsonRequestBehavior.AllowGet);
}
[HttpGet]
公共行动结果索引()
{
返回视图();
}
[HttpPost]
公共操作结果索引(字符串c、字符串p)
{
ViewBag.x=“产品:+p;
ViewBag.y=“类别”+c;
返回视图();
}
}
}
下面是我如何检索所选列表框的文本值的问题。我只能检索CategoryId的Int索引。我需要CategoryName ProductName两个字符串。这是我的观点:viewbags.x和y只返回ID。我尝试了一些事情,但我被卡住了,我做错了什么吗?我留下了一些评论,让你看看我在尝试什么
@model hiophop.Models.CarMake
@{
ViewBag.Title = "CarView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@*<h2>CarView</h2>*@
@ViewBag.y
@ViewBag.x
@using (Html.BeginForm("Index", "Car", FormMethod.Post))
{
<div>
<label for="category">Category</label>
<select id="category" name="c" class="form-control"></select>
<label for="product">Product</label>
<select id="product" name="p" class="form-control"></select>
<div id="result"></div>
<input type="submit" id="Button1" class="btn btn-default" />
</div>
}
@section scripts {
<script type="text/javascript">
$(document).ready(function () {
// Get a list of categories and a list of products of the first category.
$.getJSON('/Car/GetCategories', null, function (data) {
$.each(data, function () {
$('#category').append('<option value=' +
this.CategoryID + '>' + this.CategoryName + '</option>');
});
$.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) {
$.each(data, function () {
$('#product').append('<option value=' +
this.ProductID + '>' + this.ProductName + '</option>');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting products!');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting categories!');
});
// Dropdown list change event.
$('#category').change(function () {
$('#product option').remove();
$.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) {
$.each(data, function () {
$('#product').append('<option value=' +
this.ProductID + '>' + this.ProductName + '</option>');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert('Error getting products!');
});
});
});
//var result = $('#result');
//$(document).ready(function () {
$("#Button").click(function () {
var request = $('#category option:selected').text() + "," + $('#product option:selected').text();
$.ajax({
type: 'POST',
contentType: "application/json;charset=utf-8",
url: '/Car/Index',
//data: "{'Category':'" + document.getElementById('#category') + "','food':'" + document.getElementById('#product') + " '}",
// async: false,
// success: function (response) {
// $('#category').val('');
// $('#product').val('');
// alert("record has been saved in database");
// },
// error: function () {
// console.log('there is some error');
// }
data: { c: request },
dataType: 'json',
success: function (data) {
result.html( '#category: ' + data.CategoryName + '' + '#product' + data.ProductName)
}
});
});
//});
</script>
}
@model hiopop.Models.CarMake
@{
ViewBag.Title=“CarView”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
@*车景*@
@取景袋
@ViewBag.x
@使用(Html.BeginForm(“Index”,“Car”,FormMethod.Post))
{
类别
产品
}
@节脚本{
$(文档).ready(函数(){
//获取类别列表和第一个类别的产品列表。
$.getJSON('/Car/GetCategories',null,函数(数据){
$。每个(数据、函数(){
$('#category').append(''+this.CategoryName+'');
});
$.getJSON('/Car/GetProducts',{intCatID:$('#category').val()},函数(数据){
$。每个(数据、函数(){
$(“#产品”).append(“”+this.ProductName+“”);
});
}).fail(函数(jqXHR、textStatus、errorshown){
警报('获取产品时出错!');
});
}).fail(函数(jqXHR、textStatus、errorshown){
警报('获取类别时出错!');
});
//下拉列表更改事件。
$('#category')。更改(函数(){
$(“#产品选项”).remove();
$.getJSON('/Car/GetProducts',{intCatID:$('#category').val()},函数(数据){
$。每个(数据、函数(){
$(“#产品”).append(“”+this.ProductName+“”);
});
}).fail(函数(jqXHR、textStatus、errorshown){
警报('获取产品时出错!');
});
});
});
//var result=$(“#result”);
//$(文档).ready(函数(){
$(“#按钮”)。单击(函数(){
var请求=$(“#类别选项:选定”).text()+”,“+$(“#产品选项:选定”).text();
$.ajax({
键入:“POST”,
contentType:“应用程序/json;字符集=utf-8”,
url:“/Car/Index”,
//数据:“{'Category':'”+document.getElementById('#Category')+”,'food':“+document.getElementById('#product')+“}”,
//async:false,
//成功:功能(响应){
//$('类别').val('');
//$('产品').val('');
//警报(“记录已保存在数据库中”);
// },
//错误:函数(){
//log('有一些错误');
// }
数据:{c:request},
数据类型:“json”,
成功:功能(数据){
html(“#类别:”+data.CategoryName+“+”#产品“+data.ProductName)
}
});
});
//});
}
编辑:事实上,当我更多地查看您的代码以及您对问题的描述时,我认为您的问题甚至更早。即使单击按钮也不会触发,因为ID应该是Button1而不是button,但是表单仍然在提交,因为您的按钮是input type=submit,并且您使用Html.BeginForm()创建了表单。这将导致表单提交到默认操作(与get相同,但作为post…这就是为什么它仍然命中corre)
$('#Button1').click(function(event) {
event.preventDefault();
// Do the rest of the click event handler here
});
$('#category option:selected').text()
var postData = {
c: $('#category option:selected').text(),
p: $('#product option:selected').text()
};
data: postData
$.post('/Car/Index', postData).done(function(data) {
//Do something with the server response here
result.html( '#category: ' + data.CategoryName + '' + '#product' + data.ProductName)
});
{ "key":"value" }
var postData = { "key":"value" };
{ "c":"some value", "p":"some other value" }
var postData = {
c: $('#category option:selected').text(),
p: $('#product option:selected').text()
};
$.ajax({
type: 'POST',
//contentType: "application/json;charset=utf-8", This line is not necessary, the browser will figure it out
url: '/Car/Index',
data: postData,
//dataType: 'json', (This line is not necessary, the browser will figure it out
success: function (data) {
result.html( '#category: ' + data.CategoryName + '' + '#product' + data.ProductName)
}
});
$.post('/Car/Index', postData).done(function(data) {
result.html( '#category: ' + data.CategoryName + '' + '#product' + data.ProductName)
});