问题描述
无论如何,我还是.net的新手,我目前有2个表,即Tag和Recipe。标签具有Name
和RecipeId
,而配方具有Name
,Instructions
和 public class CreateRecipe
{
// A list of all the tags available
public List<Tag> allTags { get; set; }
// A Recipe object
public Recipe Recipe { get; set; }
}
。基本上,您可以在创建食谱时为食谱分配标签,这是我遇到的麻烦,目前仅在“创建食谱”视图上显示标签。
进行了一些研究,很显然,有多种方法可以在View上使用2个模型。我选择了viewmodel方法。 (对于我来说,最好的方法是什么?)
viewmodel类如下:
// GET: Recipe/Create
public ActionResult Create()
{
ViewBag.Message = "Create Recipe";
CreateRecipe createRecipe = new CreateRecipe();
//Convert DB Tag (table) rows (using dataLibrary.Models.Tag class) to List of MVCAPP.Models.Tag class objects
var data = TagProcessor.LoadTags();
List<Tag> tags = new List<Tag>();
foreach (var row in data)
{
tags.Add(new Tag
{
TagId = row.TagId,Name = row.Name
});
}
// Assigning createRecipe's properties
createRecipe.allTags = tags;
createRecipe.Recipe = new Recipe();
return View(createRecipe);
}
RecipeController的Create方法:
viewmodels.CreateRecipe
自动生成@model MVCApp.viewmodels.CreateRecipe
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create Recipe</h4>
<hr />
@Html.ValidationSummary(true,"",new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List","Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
的创建视图后
Tag
如您所见,它仅创建了一个“提交/创建”按钮
The auto-generated Create View
谢谢
作为参考,这里是Recipe
和 public class Tag
{
public int TagId { get; set; }
[required]
[StringLength(50,ErrorMessage = "Tag cannot be longer than 50 characters.")]
[display(Name = "Tag Name:")]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$",ErrorMessage = "Must start with a capital letter,only alphabetic characters and no spaces allowed.")]
public string Name { get; set; }
}
类
public class Recipe
{
public int RecipeId { get; set; }
[required]
[StringLength(50,ErrorMessage = "Title cannot be longer than 50 characters.")]
[display(Name = "Title:")]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$",only alphabetic characters and no spaces allowed.")]
public string Name { get; set; }
[required]
[StringLength(500,ErrorMessage = "Instructions cannot be longer than 500 characters.")]
[display(Name = "Instructions:")]
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$",only alphabetic characters and no spaces allowed.")]
public string Instructions { get; set; }
}
{{1}}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)