我有两个模型:和Picture,分别指两个表,类别和图片。类别模型具有图片模型的导航属性。
现在,我使用脚手架特性创建了一个控制器,其中包含了CRUD操作。以下为守则:
public ActionResult Create()
{
ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name");
ViewBag.PictureId = new SelectList(db.Pictures, "Id", "PictureUrl");
return View();
}自动生成的控制器操作使用SelectList在数据库中列出可用的图片条目,并将其传递给下拉列表以供选择。这不是理想的场景,因为我想要的是不能让用户上传图片,然后将引用添加到分类模型中。稍后,将条目保存到类别和图片表中。
发布于 2011-12-07 13:53:04
首先,我要感谢@NickLarsen让我相信我的理解是好的,我可以自己完成任务。
问题并不是太难,但由于我是Asp.net MVC的新手,事情有点令人费解。从一开始,我就有这样的想法:我需要一个ViewModel合并类别和价格类,然后需要一个图片上传API。但是,不知怎么的,我没能把碎片装在合适的地方。因此,在互联网上进行了多次回归和研究后,我以下列方式完成了这项任务:
发布于 2011-12-05 16:04:42
创建这样的模型:
public class FullCategoryModel
{
public HttpPostedFileBase Picture { get; set; }
public Category CategoryModel {get; set;}
}考虑到:
@using (Html.BeginForm("Create", "Category", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(model => model.Category.Name) // example, put there all category details
<input type="file" name="Picture" id="Picture" />
<input type="submit" value="Upload" /> }
然后创建动作:
[ActionName("Create")]
[HttpPost]
public ActionResult Create(FullCategoryModel model)
{
// here you can get image in bytes and save it in db,
// also all category detail are avalliable here
MemoryStream ms = new MemoryStream();
model.Picture.InputStream.CopyTo(ms);
Image picture = System.Drawing.Image.FromStream(ms);
// save in db as separate objects, than redirect
return RedirectToAction("Index", "Category");
}发布于 2011-12-02 17:11:50
我认为MVC脚手架特性将两个模型的关系看作是“多对多”。这就是为什么它为你创建了两个下拉列表。根据您的场景,您可以在不使用"Picture“模型数据的情况下创建”类别“页面,因为"Picture”是此处的主要实体。所以在图片中创建动作。
[HttpPost]
public ActionResult Create(Picture picture)
{
if (ModelState.IsValid)
{
databaseContext.Pictures.Add(picture);
databaseContext.SaveChanges();
return RedirectToAction("Index");
}
return View(picture);
}在“创建图片”的视图页中
@model YourProjectName.Models.Picture
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Url)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Url)
@Html.ValidationMessageFor(model => model.Url)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Categories.CategoryID, "Category")
</div>
<div class="editor-field">
@Html.DropDownList("CategoryID", "Choose Category")
@Html.ValidationMessageFor(model => model.Categories.CategoryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}https://stackoverflow.com/questions/8310746
复制相似问题