I’am using ASP.NET MVC 4 with EF, I have a PostController with the Index and Create views. I would like to have both on the same page for adding a post, and visualize it on the same page. How can I do it ?
Thanks for your advices
___EDIT__
Controller :
public ActionResult Index()
{
return View(db.Posts.ToList());
}
[HttpGet]
public ActionResult Create()
{
return PartialView("_Create", **Here I can't declare model**);
}
[HttpPost]
public ActionResult Create(FormCollection values)
{
var post = new Post();
TryUpdateModel(post);
if (ModelState.IsValid)
{
/** somme code **/
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View("_Create", post);
}
My _Create partial view :
@model MyProject.Models.Post
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
/**some stuff **/
}
my Index View :
@model IEnumerable<MyProject.Models.Post>
@{
ViewBag.Title = "Index";
}
<p>
/** some stuff **/
</p>
@Html.Partial("_Create", **Here I can't declare model**)
And my Post Model :
public int PostId { get; set; }
public int UserId { get; set; }
public string Content { get; set; }
It tells me that “The model item passed into the dictionary is of type ‘System.Collections.Generic.List`1[MyProject.Models.Post]’ but this dictionary requires a model item of type ‘MyProject.Models.Post‘.
It really depends on how your code looks right now. If you have a separate
Createaction method returning aPartialView, like so:Then in your view you would use
Html.RenderAction()where you want the_Createpartial view to be displayed:If you don’t have a separate action method for
Createand just have a partial view to make things cleaner, then simply usingHtml.Partial()in yourIndexview will do the trick:Update
After looking through your code, there are two ways you can do it (I’ll show you both). Your problem occurs because you’re passing a list of posts to your
Indexview while your_Createpartial view requires a singlePostmodel. Since you aren’t explicitly passing a model to the partial view when you’re calling it, it automatically tries to use the model in theIndexview (your list of posts). The first way to solve the problem requires minimal changes to your code.Change your
Createaction method as follows:Then in your
Indexview, use:The second method is to use a view model that exposes the list of posts to display on the
Indexview, and also has an “empty”Postmodel that can be used to create a new post in the_Createpartial view. I prefer this method, but it’s your call.Your view model:
Your
Indexaction method:Your
Indexview:Your
_Createpartial view will remain the same.