简体   繁体   中英

Following the MVC4 tutorial, where does “Model” come from and how can I change it's value?

VisualStudio2010 tells me that it's the Model Property associated with System.Mvc.ViewDataDictionary Object which is helpful, but the docs for DataDictionary don't seem to show me what I want, in an easily understood format, at least.

Note that the following .cshtml file is in BorkedModel 's View folder, but the model I want to access is in ExampleModel 's Model folder. This exact code would work if the file itself was in the ExampleModel 's View folder, but not in a different model's View folder.

ProjectTopDirectory/Views/ BorkedModel /index.cshtml

 @model IEnumerable<ExampleMVC4.Models.ExampleModel> @foreach (var item in Model) { <HTML here/> } 

Is there a solution to what I'm doing, or should I just keep models in their own view, and that's it? Is there a way to access one Model from another Model's View?

To use a strongly typed model in a view you need to pass the model to the view from the controller:

public ActionResult Index()
{
    YourDBContext db = new YourDBContext();
    IEnumerable<ExampleModel> model = db.GetDataFromDatabase();
    return View(model); // Pass the model to the view
}

Then in your view you specify the model, which should allow you to access the data:

@model IEnumerable<NextFlicksMVC4.Models.ExampleModel>

@foreach (var item in Model)
{
    // Your HTML
}

UPDATE: Your controller action method should be retrieving the data from the database and then passing it to the View. The view's only job is to display the data to the user.

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