嗨,我有MVC Razor应用程序作为电子目录,我使用下拉列表绑定来自DB的数据,但DDl绑定来自DB的相同值,就好像我有三个类别“x、Y、Z” DDL返回相似的值“Z ,Z , Z "。因为它有最后一个值 "y" 。当用户从DDL中选择项目时,我也尝试将选定的值“ID”插入 DB,但我不能,它返回错误的选定值。
public class CategoryController : Controller
{
private AndriodContext db = new AndriodContext();
List<SelectListItem> items = new List<SelectListItem>();
List<string> category = new List<string>();
SelectListItem s = new SelectListItem();
//
// GET: /Category/
public ActionResult Index()
{
var x = db.Categories.Where(y => y.Active == true).ToList();
return View(x);
}
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
List<string> x = new List<string>();
foreach (var t in data)
{
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
//
// POST: /Category/Create
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
var data = db.Categories.ToList().Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in data)
{
SelectListItem s = new SelectListItem();
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
if (s.Selected)
{ category.Parent_ID = int.Parse(s.Value); }
}
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
}
@using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data", @data_ajax = "false" })) { @Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-field create-Bt3">
@Html.DropDownList("Parent", new SelectList(ViewBag.Parent, "Value", "Text"), "- Select Parent -")
</div>
<div>
<p class="create-Bt ">
<input type="submit" value="Create" />
</p>
</div>
<br />
<br />
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</fieldset>
}