简体   繁体   English

视图模型和PartialView问题MVC C#

[英]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. 我对C#/ MVC还是比较陌生,并且对某些基本的知识一无所知,因此,一个或两个有用的人可以帮助我。 What i am trying to work out is the concept with Viewmodels and partials View. 我要尝试的是使用Viewmodels和局部视图的概念。 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'? 我想创建一个包含我的视图模型中所有书籍的列表,然后将其解析为partialView,这是一个好方法还是应该为“书架”创建一个普通的类?

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 下面的代码给我以下错误atm:错误CS1001:预期的标识符

//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. 不知道您的推理在哪里,通常使用局部视图来呈现页面的某些重复部分或通过ajax加载的页面的某些部分。

Also the foreach loop is wrong. 而且foreach循环是错误的。 You need the following: 您需要以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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