如何在mvc4

时间:2015-11-17 06:30:06

标签: asp.net sql-server asp.net-mvc-4

我有两张桌子

1- P_Product

2- P_Imagepath

我想在P_Product表中存储输入数据,并根据第一个表的ID。我想用P_Product Id将图像存储到P_Imagepath表中。

我在这里试过,但它显示了一些错误

  

在Foreach循环中,它显示"新表达式需要(),[],{}   类型"和" item"它的节目不能无意中转换类型   System.web.HttpPostedFileBase到string

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(P_Product p_product,List<HttpPostedFileBase> Base)
        {      
            if (ModelState.IsValid)
            {
                db.P_Product.Add(p_product);                
                db.SaveChanges();
                P_Product product = db.P_Product.LastOrDefault();
                int p = product.Id;
                List<P_ImagePath>images=new List<P_ImagePath>
                foreach(var item in Base)
                {
                    P_ImagePath image=new P_ImagePath();
                    image.P_Id=p;
                    image.ImagePath=item;
                    images.Add(image);
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Cat_Id = new SelectList(db.P_Category, "Id", "Name", p_product.Cat_Id);           
            return View(p_product);
        }

1 个答案:

答案 0 :(得分:0)

//this line has syntax error - missing "();"
//correct form: List<P_ImagePath>images=new List<P_ImagePath>();
List<P_ImagePath>images=new List<P_ImagePath> 

你的 image.ImagePath 可能是字符串(它是),而 item 是来自基本列表的项目,这意味着该项目的类型为 HttpPostedFileBase (方法参数),因此您无法将其转换为字符串。

您可以做的是从项目中查找该文件的路径。所以,试试这个:

...
foreach(var item in Base)
{
    P_ImagePath image=new P_ImagePath();
    image.P_Id=p;
    image.ImagePath= Path.GetFileName(item.FileName);
    images.Add(image);
}
相关问题