我还在学习ASP.NET / MVC,并按照Matt Blagden(You Tube)的教程建立博客......
制作后置控制器后,我在一段代码中遇到错误,如果它是一个新帖子,它会处理向帖子添加标签。我的想法是当我添加新的实体数据模型时应该生成AddToPosts的方法。
错误是:
blog.Models.BlogModel不包含“AddToPosts”的定义,也没有“AddToPosts”的扩展方法。可以找到接受类型为“blog.Models.BlogModel”的第一个参数的PostsController.cs(您是否缺少using指令或程序集引用?)
给我错误的代码部分是:
if (!id.HasValue)
{
model.AddToPosts(post);
}
这是整个Post Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using blog.Models;
using System.Data.EntityModel;
using System.Text;
namespace blog.Controllers
{
public class PostsController : Controller
{
// Access Model
private BlogModel model = new BlogModel();
public ActionResult Index()
{
return View();
}
// A way to input sample data into database
[ValidateInput(false)]
public ActionResult Update(int? id, string title, string body, etc.....)
{
//IF not an admin redirect back to index
if (!IsAdmin)
{
return RedirectToAction("Index");
}
// Get Post
Post post = GetPost(id);
// Populate simple properties
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear(); // first clear tag list
//ensure input sequence of tag names is not null
tags = tags ?? string.Empty;
//Split the sequence into a list of tag names
string[] tagNames = tags.Split(new char[] { ' ' }, etc...
//Get or create each tag that was named
foreach (string tagName in tagNames)
{
//Add the tag
post.Tags.Add(GetTag(tagName));
}
if (!id.HasValue)
{
model.AddToPosts(post);
}
model.SaveChanges();
return RedirectToAction("Details", new { id = post.ID });
}
// PROMPTS USER TO INPUT DATA FOR DATABASE
public ActionResult Edit(int? id)
{
Post post = GetPost(id);
//ACCUMULATES LIST OF CURRENT TAGNAMES
StringBuilder tagList = new StringBuilder();
foreach (Tag tag in post.Tags)
{
//Append each tagname
tagList.AppendFormat("{0} ", tag.Name);
}
//Gives the tagList to the view
ViewBag.Tags = tagList.ToString();
return View(post);
}
private Tag GetTag(string tagName)
{ // if tag is set then Get the Tag, if not create a new one (Just like GetPost)
return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? etc....
}
private Post GetPost(int? id)
{
// IF id is set then Get the Post, if not make a new one..
return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : etc.....
// TODO: don't just return true
public bool IsAdmin
/* READS SESSION STATE */
{
get { return true; /*{ return Session["IsAdmin"] != null && etc...
}
}
}
答案 0 :(得分:0)
如果“AddToPosts”来自静态类,请尝试使用添加后期类所在的命名空间语句添加。