C# 在控制器中获取选择值
我需要在控制器中获取Select值C# 在控制器中获取选择值,c#,html,asp.net-core,C#,Html,Asp.net Core,我需要在控制器中获取Select值 变量“”中的strDDLValue 我试着去做,但没用 [HttpPost] public async Task<IActionResult> Create(AddItemViewModel model, IFormCollection form) { if(ModelState.IsValid) { string strDDLValue = Request.Form["sel
变量“”中的strDDLValue 我试着去做,但没用
[HttpPost]
public async Task<IActionResult> Create(AddItemViewModel model, IFormCollection form)
{
if(ModelState.IsValid)
{
string strDDLValue = Request.Form["selectCategory"].ToString();
[HttpPost]
公共异步任务创建(AddItemViewModel模型,IFormCollection表单)
{
if(ModelState.IsValid)
{
string strDDLValue=Request.Form[“selectCategory”].ToString();
html
自动完成
<script type="text/javascript">
$.ajax({
type: 'GET',
url: '/Item/GetItemCategories',
dataType: 'json',
success: function (category) {
$.each(category, function (key, value) {
$('#selectCategory')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
});
</script>
$.ajax({
键入:“GET”,
url:“/Item/GetItemCategories”,
数据类型:“json”,
成功:功能(类别){
$。每个(类别、功能(键、值){
$(“#选择类别”)
.append($(“”)
.attr(“值”,键)
.文本(值));
});
}
});
检查是否在ajax回调中正确填充了select标记帮助程序。以下是工作示例:
GetCountry控制器及其在ajax中的成功功能
public JsonResult GetCountry()
{
var country = _context.Country.ToList();
return Json(new SelectList(country,"Id","CountryName"));
}
success: function (result) {
$("#selectCountry").empty();
$.each(result, function (i, item) {
$("#selectCountry").append('<option value="' + item.value + '"> ' + item.text + ' </option>');
});
表单数据保存为请求中的键值对,您可以获得selectCountry的值,如下所示
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
//In that case, you could iterate over your dictionary or you can access values directly:
var ddl = dict["selectCountry"];
您能详细说明“不起作用”的含义吗?变量“”中的strDDLValue那么您如何提交表单?您向我们展示的操作方法没有用
[HttpPost]
挂起[HttpPost]来修饰
<select class="browser-default custom-select" name="selectCountry" id="selectCountry"> </select>
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
//In that case, you could iterate over your dictionary or you can access values directly:
var ddl = dict["selectCountry"];