Answer the question
In order to leave comments, you need to log in
ViewModel how to pass multiple models?
How to pass multiple models to ViewModel
1) Example of one of the models
public class NewsEntity : TableServiceEntity
{
public NewsEntity()
{
int y = 9999 - DateTime.Now.Year;
int m = 13 - DateTime.Now.Month;
PartitionKey = string.Format("{0}_{1}", y,m);
RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks, Guid.NewGuid());
}
//Статья
[DisplayName("Описание статьи")]
public string Description { get; set; } // Description - Описание статьи
public class NewsRepository
{
private static CloudStorageAccount storageAccount;
private NewsContext context;
static NewsRepository()
{
storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudTableClient.CreateTablesFromModel(
typeof(NewsContext),
storageAccount.TableEndpoint.AbsoluteUri,
storageAccount.Credentials);
}
public NewsRepository()
{
this.context = new NewsContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
this.context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
}
#region CRUD Operations
public void AddNews(NewsEntity newNews)
{
newNews.ViewCount = 0;
newNews.Votes = 0;
newNews.Raiting = 0;
newNews.AddedDate = DateTime.UtcNow;
this.context.AddObject("NewsEntry", newNews);
this.context.SaveChangesWithRetries();
}
public class HomeController : Controller
{
private NewsRepository _repo = new NewsRepository();
private SlideRepository _slider = new SlideRepository();
public ActionResult Index()
{
// var model = _slider.ListSlide(); как работает с одной моделью
Что должно быть здесь при выводе нескольких моделей? =)
return View(model);
}
Answer the question
In order to leave comments, you need to log in
Model
public class NewsViewModel{
public IEnumerabe<NewsEntity> News{get;set;}
public SliderEntity Slider{get;set;}
}
public ActionResult Index(){
var model = new NewsViewModel(){
News=_repo.NewsEntities.Where(...).AsIEnbumerable(),
Slider=_slider.Slider.Single(...)
};
return View(model);
}
@model NewsViewModel
Слайдер
@Model.Slider
Новости
@foreach(var item in Model.News){
....
}
You can make a wrapper class for several models and pass it to the View. Or don't use a strongly typed View.
Well, firstly, if all NewsEntity objects are objects of the same class, or their classes are inherited from the same class, then you can do this:
@model IEnumerable<BaseEntity>
ViewBag.NewsEntity = new NewsEntity( /* ... */ );
ViewBag.OtherEntity = new OtherEntity( /* ... */ );
ViewBag.NewsEntity....
From the point of view of the mvc architecture, it’s probably worth creating a ViewModel that contains everything, from the point of view of quick writing, I passed it to View Tuple<Model1,Model2,Model3>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question