1

I am trying to display the selected value in view. I am selecting a year in my view and passing that value to controller to filter my records. And again I need to pass that value to my view to display which value or year I selected. I don't have problem with filtering my record. My problem is I need to display which Year I selected. How do I do that?

When I run my application I am getting

System.InvalidOperationException: The model item passed into the dictionary is of type 'MyRecords.Models.ModelYear', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[MyRecords.Models.RecordsList]'.

Herer is my code.

Index View

@model List<MyRecord.Models.RecordList>



var year = DateTime.Now.Year;
for (var i = year; i > 2012; i--)
{
    var j = @i - 1;
    <div class="col-md-1 ">
        @Html.ActionLink(i.ToString(), "MyPage", new { i = i })
    </div>
}

// Here I am Displaying which year I selected like 2010 and records of 2010

<h3>@ModelYear.Year</h3> 
@foreach (var groupMonth in Model.GroupBy(recordLists => new { recordLists.date.Value.Year, recordLists.date.Value.Month }))
{
    <h3 class="monthHeader"> @System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(groupMonth.Key.Month)</h3>
    foreach (var recordLists in groupMonth)
    {
        <div class="row">
            @Html.Partial("_PartialView", recordList)
        </div>
    }
}

Controller

public ActionResult Archives(int i = 0)
{
    var recordLists = new List<RecordList>();

    if(i == 0)
        recordLists = _db.recordlists
            .Where(p => p.date.Value.Year == DateTime.Now.Year)
            .OrderByDescending(p => p.date)
            .ToList();
    else
        recordLists = _db.recordlists
            .Where(p => p.date.Value.Year == i)
            .OrderByDescending(p => p.date)
            .ToList();

     return View(new ModelYear{Records = recordLists, Year = i});
}

Model:

namespace MyRecord.Models

{

using System;
using System.Collections.Generic;

public partial class RecordList {

    public int id { get; set; }
    public string title { get; set; }
    public Nullable<System.DateTime> date { get; set; }
}

public class ModelYear
{
    public int Year { get; set; }

    public List<RecordList> Records { get; set; }
}

}

Hob
  • 139
  • 1
  • 13

1 Answers1

1

based on comments

1) change in view model @model List on @model List

2) new model contains data year and recordlist, you can put inside what all you want.

you only need to remember that the model is hierarchical and not flat

foreach (var groupMonth in Model.RecordList.GroupBy(recordLists => new { recordLists.date.Value.Year, recordLists.date.Value.Month }))
Eduard M
  • 247
  • 2
  • 9