发布表单

时间:2016-02-03 01:50:56

标签: asp.net asp.net-mvc razor

我正在开发一个简单的图片上传网站,用户可以在上传到网站的图片上发表评论,每当发布评论我都会收到此错误:

  

传入字典的模型项的类型为'<> f__AnonymousType1`1 [System.Int32]',但此字典需要类型为' SilkMeme.Models的模型项.Meme&#39 ;.

我知道这与我在视图顶部定义的模型与我发送帖子请求的模型有所不同,但我并不完全确定如何修复它

查看

@model SilkMeme.Models.Meme
....
@using (Html.BeginForm("Comment", "Memes", new { id = Model.SilkId }))
{
    <label for="thought">Thoughts?</label>
    <input type="text" name="thought"/>
    <label for="rating">Rating?</label>
    <input name="rating" type="range" min="0" max="10" step="1" /> 
    <input type="submit" value="Post Thoughts" />
}
<div class="thoughts">
    @foreach (var c in ViewBag.thoughts)
    {
        <p>- @c.ThoughtWords , @c.ThoughtRating / 10 meme</p>
    }
</div>

控制器

public ActionResult Details(int? id)
{
    var thoughts = from comment in db.Thoughts where comment.SilkId == id select comment;
    ViewBag.thoughts = thoughts;
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Meme meme = db.Memes.Find(id);
    if (meme == null)
    {
        return HttpNotFound();
    }
    return View(meme);
}

[HttpPost]
public ActionResult Comment(int id)
{
    int thoughtid = (from m in db.Thoughts select m).OrderByDescending(e => e.ThoughtId).FirstOrDefault().ThoughtId + 1;
    if (Request["thought"].ToString() != "")
    {
        Thought thought = new Thought()
        {
            ThoughtId = thoughtid,
            SilkId = id,
            Meme = db.Memes.Find(id),
            ThoughtWords = Request["thought"],
            ThoughtRating = Int32.Parse(Request["rating"])
        };
        db.Thoughts.Add(thought);
    }
    return View("Details", new { id = id });
}

1 个答案:

答案 0 :(得分:1)

这一行。

return View("Details", new { id = id });

它基本上将带有Id属性的匿名对象传递给您的视图,该视图强类型为Meme类型,并且期望对象为Meme类。

如果您成功保存数据,理想情况下,您应该重定向到GET操作(在 PRG 模式之后)

[HttpPost]
public ActionResult Comment(int id)
{
    int thoughtid = (from m in db.Thoughts select m)
                      .OrderByDescending(e => e.ThoughtId).FirstOrDefault().ThoughtId + 1;
    if (Request["thought"].ToString() != "")
    {
        Thought thought = new Thought()
        {
            ThoughtId = thoughtid,
            SilkId = id,
            Meme = db.Memes.Find(id),
            ThoughtWords = Request["thought"],
            ThoughtRating = Int32.Parse(Request["rating"])
        };
        db.Thoughts.Add(thought);
        db.SaveChanges();
    }
    return RedirectToAction("Details", new { Id=id });
}

另外,我建议使用MVC Modelbinding来读取提交的表单数据。你会在stackoverflow上找到大量的例子来做到这一点。使用ModelBinding时,可以将发布的视图模型返回到视图(如果需要,可以显示错误消息),ValidationSummary / ValidationMessgeFor帮助器方法可以根据需要向用户显示错误消息。