嗨,我有一个项目,我的任务之一就是插入所选的值 通过razor mvc下载到DB字段。我做了我的代码,但没有插入值,DDL也有来自DB的项目。我用razor mvc4的项目。
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
foreach (var t in data)
{
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
if (Request.Files.Count > 0)
{
var uploadedFile = Request.Files[0];
var fileSavePath = "";
var fileName = "";
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
category.Path = "~/App_Data/Uploads/" + fileName;
}
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");
}
答案 0 :(得分:0)
您正在同一个循环中创建新的selectListItem。对于任何项目,您将获得seleced == true。
如果是您的模型绑定到所需的下拉列表,那么用户在UI上选择的项目(发布前)可能存在于类别参数中。
我怀疑这是一个逻辑错误。
问候,马赫什
答案 1 :(得分:0)
您好您的代码应该是这样的。我假设你有一定的结构模型。如果belo代码没有给你一个线索,那么请。告诉您的视图和模型是什么以及您的要求是什么。
希望这有帮助。
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
if (Request.Files.Count > 0)
{
var uploadedFile = Request.Files[0];
var fileSavePath = "";
var fileName = "";
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
category.Path = "~/App_Data/Uploads/" + fileName;
}
var data = db.Categories.ToList().Distinct();
//I assume that you need to find the category from db.Caegories which user has selected on the UI and submited the form.
//I assume the parameter category is the one which you want to find from DB.
//category is your model has Parent_Id property which is bound to UI control (ie. dropdown)
var categoryToSave = (from c in data
where c.Cat_ID == category.Parent_ID
select c).firstOrDefault();
if(categoryToSave!=null)
{
//I believe here you want to save this category to some other table.
//Now you have got the category tht user has selected on UI.
//Write the further logic here.....
db.SaveChanges();
}
return RedirectToAction("Index");
}
问候,马赫什