我使用mvc 5进行学习。 当我从下拉列表中发送控制器上的数据时,对象在控制器中具有空值。
namespace Dropdownlist.Models
{
using System;
using System.Collections.Generic;
public partial class Country
{
public int ID { get; set; }
public string CountryName { get; set; }
}
}
namespace Dropdownlist.Controllers
{
public class HOMEController : Controller
{
DropDownEntities db = new DropDownEntities();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Country cn)
{
db.Countries.Add(cn);
db.SaveChanges();
return View(cn);
}
}
}
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm(FormMethod.Post))
{
<div>
@Html.DropDownList("ddlcountry", new List<SelectListItem>
{
new SelectListItem{ Text = "India", Value = "India"},
new SelectListItem{ Text = "UK", Value = "UK"},
new SelectListItem{ Text = "USA", Value = "USA"}
}, "Select a Country")
</div>
<div>
<input type="submit" value="Save" />
</div>
}
我做错了什么?
答案 0 :(得分:1)
如果您希望回发ID
和CountryName
值,那么您需要让控件名称与模型的属性相匹配,并且您的视图应该是强类型的,以便您可以使用Html.DropDownListFor()
助手,现在就可以这样做:
@model Dropdownlist.Models.Country
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm(FormMethod.Post))
{
<div>
@Html.DropDownList("ID", new List<SelectListItem>
{
new SelectListItem{ Text = "India", Value = 1},
new SelectListItem{ Text = "UK", Value = 2},
new SelectListItem{ Text = "USA", Value = 2}
}, "Select a Country",new { id="ddlCountry"})
@Html.Hidden("CountryName")
</div>
<div>
<input type="submit" value="Save" />
</div>
}
和countryName您需要在隐藏字段中设置它并在下拉索引更改时设置它的值,如下所示:
@section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCountry").on("change", function () {
$("#CountryName").val($(this).val());
});
});
</script>
}
答案 1 :(得分:0)
如果要设置CountryName
属性,请将视图更改为:
....
@Html.DropDownListFor(x=>x.CountryName, new List<SelectListItem>
....
答案 2 :(得分:0)
答案 3 :(得分:0)
加载您从控制器下载数据
ViewBag.DropDown = db.YourModel.ToList();
然后在你的视图中
@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.DropDown, "Select ...")
答案 4 :(得分:0)
这里有几个问题,但我认为你的事情是这样的:
您的选择列表项的枚举:
public enum Countries
{
India = 1,
UK = 2,
USA = 3
}
然后是控制器动作:
public ActionResult Index()
{
ViewBag.Country = Enum.GetValues(typeof(Countries)).Cast<Countries>().ToList().Select(r => new SelectListItem { Text = r.ToString(), Value = ((int)r).ToString() });
return View();
}
[HttpPost]
public ActionResult Index(Countries country)
{
var saveit = country;
// whatever you wish to do with the result;
return Content(saveit.ToString());
}
观点:
@using(Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownList("Country")
<button type="submit" >Save</button>
}