【问题标题】:failed in data insertion in asp.net mvc3在 asp.net mvc3 中插入​​数据失败
【发布时间】:2012-04-30 05:48:43
【问题描述】:

我有一张桌子

 post(p_id,u_id(FK),date,title,type,viewer)
和一个带有(p_id,u_id,date,title,type)的Modelclass UserModel.cs。当我在帖子控制器中创建新帖子时,我尝试了
 public ActionResult Create(PostModel p)
        {

        if (ModelState.IsValid)
        {
          p.date =  DateTime.Today;
          post post = new Models.DB.post();
          post.u_id = User.Identity.Name;
          post.date = p.date;
          post.title = p.title;
          post.type= p.type;
          post.viwer=1;

          try{      db.posts.AddObject(post);
                db.SaveChanges();
         return RedirectToAction("LoggedIndex");
         }
        catch{ return RedirectToAction("Index"); }
      }
    return View(p);
   }

它不工作。我认为从不提交时我提交总是返回视图。我创建了 stronly 类型的创建视图。在 create.cshtml 中,我有两个隐藏字段 user_id 和 postModel 对象的日期。我是 MVC 的新手。请帮助我提前谢谢....

【问题讨论】:

  • 是否要将数据保存到数据库中?

标签: asp.net-mvc-3


【解决方案1】:

使用 MVC 模型将数据从视图发送到控制器

我是这样理解的:你有一个 mvc3 页面,想向你的控制器发送一些自定义数据:

控制器:

[http-post]
    public ActionResult Create(PostModel p)
        { 
        if (ModelState.IsValid)
        {
          p.date =  DateTime.Today;
          post post = new Models.DB.post();
          post.u_id = User.Identity.Name;
          post.date = p.date;
          post.title = p.title;
          post.type= p.type;
          post.viwer=1;

                db.posts.AddObject(post);
                db.SaveChanges();
         return RedirectToAction("LoggedIndex");
      }
    return View(p);
   }

public ActionResult Create()
        { 

    return View(new post());
   }

查看:

@model post

@using (Html.BeginForm("Create", "Controller-Name", FormMethod.Post, new { id = "FORM" }))
{
 @Html.EditorFor(model => model.date)

 @Html.EditorFor(model => model.name)

 @Html.EditorFor(model => model.title)

 @Html.EditorFor(model => model.type)
}

更多信息:http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

【讨论】:

  • 谢谢 其实这是一个非常愚蠢的错误...
    public ActionResult Create() { return View(new post()); } 
    我没有 return new post() 我被写了
    return View()
猜你喜欢
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多