简体   繁体   中英

Viewmodels and PartialView problems MVC C#

I am fairly new to C#/MVC and are stuck understanding some propably basic stuff so maybe a helpfull soul or two can help me out. What i am trying to work out is the concept with Viewmodels and partials View. I want to create a list containing all my books in my viewmodel and parse that to the partialView, is that a good way or should I just make an ordenary class for the 'bookshelf'?

Anyway I cant get my 'bookshelf' showed in my partial view and have gotten quite different errors, so im a bit lost on where to start troubleshooting.

Beneath code are giving me following error atm: error CS1001: Identifier expected

//In my Model folder
Public class Book
{
public int ID       { get; set; }
public string Name  { get; set; }
public int Pages    { get; set; }
}

//In my ViewModel folder
public class BookshelfVM
{
public List<Book> Books { get; set; }
}

//Controller action

public class BookshelfController : Controller
{
public ActionResult ListBook()
{
  BookshelfVM Viewmodel = new BookshelfVM();

        Viewmodel.Books = new List<Book>()
        {
            new Book()
            {
                ID = 1,
                Name = "How to...",
                Pages = 312
            },
            new Card()       
            {
                ID = 2, 
                Name = "How to... two",  
                Pages = 512
            }
        };
        return View("_ListBook", Viewmodel);
}
}

//View
@model How.ViewModels.BookshelfVM
@{
ViewBag.Title = "Bookshelf";
}
Lorem ipsum
<div>
    <p>
        @Html.Partial("_ListBook")</p> *error pointing here
</div>

//Partial View
@model How.ViewModels.BookshelfVM

@foreach (var Book in How.Models.)
{
<div>

    @Model.Book
</div>
}

You need to pass the model to your partial view. Instead of:

@Html.Partial("_ListBook")

you need:

@Html.Partial("_ListBook", Model)

Although it is a bit confusing why your controller action is also returning the same partial view. Don't know what your reasoning is there partial views are generally used to render some segment of the page that repeats or some segment of the page that is loaded via ajax.

Also the foreach loop is wrong. You need the following:

@foreach (var book in Model.Books)
{
   <div>@book.Name</div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM