0

I'm trying to populate Month and Year in asp.net mvc project's cshtml view page

this is the view page code

@model IEnumerable<project.Models.ProductStatistics>

@{

 }

@Html.DropDownList("ExpirationMonth", ExpirationMonthDropdown)
@Html.DropDownList("ExpirationYear", ExpirationYearDropdown)

this is the model

public class ProductStatistics
{

    public IEnumerable<SelectListItem> ExpirationMonthDropdown
    {
        get
        {
            return Enumerable.Range(1, 12).Select(x =>

                new SelectListItem()
                {
                    Text = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[x - 1] + " (" + x + ")",
                    Value = x.ToString(),
                    Selected = (x == Model.ExpirationMonth)
                });
        }
    }

    public IEnumerable<SelectListItem> ExpirationYearDropdown
    {
        get
        {
            return Enumerable.Range(DateTime.Today.Year, 20).Select(x =>

            new SelectListItem()
            {
                Text = x.ToString(),
                Value = x.ToString(),
                Selected = (x == Model.ExpirationYear)
            });
        }
    }

}

but here I'm getting following error in Model Class

The name 'Model' does not exist in the current context

also getting this error in view page

The name 'ExpirationMonthDropdown' does not exist in the current context

kez
  • 2,273
  • 9
  • 64
  • 123
  • 5
    There's a lot wrong with this code. The first error is obvious: you're accessing `Model` in your `ProductStatistics` methods, which does not exist there. `Model` only exists as a member variable in views. The second error is because your view's model is `IEnumerable`, so even if you were to use `Model.ExpirationMonthDropdown`, it won't work, because enumerable != 1. Please show some more relevant code. – CodeCaster Feb 25 '16 at 09:47
  • @CodeCaster do I need to move `ExpirationMonthDropdown` and `ExpirationYearDropdown` methods to controller method – kez Feb 25 '16 at 09:51
  • 1
    No, you need to show more code, for example where `ExpirationMonth` and `ExpirationYear` are defined. – CodeCaster Feb 25 '16 at 09:58
  • The first error is thrown by your line `Selected = (x == Model.ExpirationMonth)` (x2) becuse your model does not contain a property name `Model`. But since you binding to a property name `ExpirationMonth`, then its ignored anyway so just delete it. –  Feb 25 '16 at 11:26
  • The second error is because you have not defined `IEnumerable` properties in the view named `ExpirationMonthDropdown` and `ExpirationYearDropdown` - but you use of `@model IEnumerable` in the view makes no sense so impossible to understand what you think your trying to do –  Feb 25 '16 at 11:30
  • @StephenMuecke simply i want to populate two dropdowns for month and year , I just followed [4th answer of this question's](http://stackoverflow.com/questions/812330/what-is-the-best-way-to-code-up-a-month-and-year-drop-down-list-for-asp-net) – kez Feb 26 '16 at 04:02
  • Not sure why that answer got any up votes - it simply does not work. shu's answer should put you on the right track (so long as you change the model to `@model ProductStatistics` (not `IEnumerable`). But if your model is a collection, then you need to use a loop to iterate through each item in the collection. –  Feb 26 '16 at 04:13
  • And have you abandoned your [previous question](http://stackoverflow.com/questions/35601002/model-property-multiselectlist-values-store-in-javascipt)? –  Feb 26 '16 at 04:15
  • @StephenMuecke no combination between this question and previous one – kez Feb 26 '16 at 04:27
  • Its just that you never added the script and the controller method in that question in order to add an answer –  Feb 26 '16 at 04:31

1 Answers1

5

Change your model with following code

public class ProductStatistics
{

   [Display(Name = "Product ID")]
    public string Product_ID { get; set; }

   [Display(Name = "Product Name")]
    public string ProductName { get; set; }
}

public class ProductStatisticsList
{
    public List<ProductStatistics> Products
    {
        get;
        set;
    }

    public int SelectedMonth
    {
        get;
        set;
    }
    public int SelectedYear
    {
        get;
        set;
    }
}

In the action

public ActionResult Index()
{
   ViewBag.Months = new SelectList(Enumerable.Range(1, 12).Select(x =>
      new SelectListItem()
              {
                  Text = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[x - 1] + " (" + x + ")",
                  Value = x.ToString()
              }), "Value", "Text");



        ViewBag.Years = new SelectList(Enumerable.Range(DateTime.Today.Year, 20).Select(x =>

           new SelectListItem()
           {
             Text = x.ToString(),
             Value = x.ToString()
           }), "Value", "Text");

      ProductStatisticsList p = new ProductStatisticsList();
     // p.Products = new List<ProductStatistics>();
      //p.Products.Add(new ProductStatistics { Product_ID = "Product_ID", ProductName = "ProductName" });
      p.Products = (from productstatistics in db.ProductStatistics

                    select new ProductStatistics
                    {
                        Product_ID = productstatistics.Product_ID,
                        ProductName = productstatistics.ProductName,

                    }).ToList();



        p.SelectedMonth = 3;
        return View(p);
 }


    [HttpPost]
    public ActionResult Index(ProductStatisticsList model)
    {
        //do the stuff
    }

in your view

@model project_name.Models.ProductStatisticsList

@{

 }

  @using (Html.BeginForm("index", "Home", FormMethod.Post, new { id = "formIndex" }))
{

    @Html.DropDownListFor(model => model.SelectedMonth, (IEnumerable<SelectListItem>)ViewBag.Months, "Month") 
    @Html.DropDownListFor(model => model.SelectedYear, (IEnumerable<SelectListItem>)ViewBag.Years, "Year") 

    <table class="table">
        @if (Model.Products != null && Model.Products.Count > 0)
        {

            <tr>
                 <th>
                    @Html.DisplayNameFor(modelItem => Model.Products[0].Product_ID) @*This approch is wrong , should read from resource file*@
                </th>
                <th>
                    @Html.DisplayNameFor(modelItem => Model.Products[0].ProductName) @*This approch is wrong , should read from resource file*@
                </th>               
           </tr>

            for (var i = 0; i < Model.Products.Count; i++)
            {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => Model.Products[i].Product_ID)
                    @Html.HiddenFor(modelItem => Model.Products[i].Product_ID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => Model.Products[i].ProductName)
                    @Html.HiddenFor(modelItem => Model.Products[i].ProductName)
                </td>
            </tr>
            }
        }
    </table>

    <input type="submit" value="submit" />
}
shu
  • 1,938
  • 10
  • 19
  • then I'm getting following error `'IEnumerable' does not contain a definition for 'ExpirationMonthDropdown' and no extension method 'ExpirationMonthDropdown' accepting a first argument of type 'IEnumerable'` – kez Feb 26 '16 at 03:58
  • @kez your model should be `ProductStatistics` not `'IEnumerable – shu Feb 26 '16 at 03:59
  • pardon me to mention this in this model I have table also , to post as a simple question just left code snippet like this , once I made to `@model project.Models.ProductStatistics` getting following error `foreach statement cannot operate on variables of type 'project.Models.ProductStatistics' because 'project.Models.ProductStatistics' does not contain a public definition for 'GetEnumerator'` – kez Feb 26 '16 at 04:34
  • Ok in that case we need to fill the combo box using `ajax` or `viewbag` – shu Feb 26 '16 at 04:38
  • I cannot understand you said , can I have an example – kez Feb 26 '16 at 04:39
  • can you please post your `action` method – shu Feb 26 '16 at 04:41
  • @kez, If you model is a collection, then it needs to be `for(int i = 0; i < Model.Count; i++) { @Html.DropDownListFor(m => m[i].ExpirationMonth, Model[i].ExpirationMonthDropdown, "Months") }` and it needs to be `@model IList` (not `IEnumerable`). But if that is the case, you need to show more code –  Feb 26 '16 at 04:43
  • @StephenMuecke yes are absolutely correct, if the model is a collection. – shu Feb 26 '16 at 04:49
  • @shu this is the whole [code segments](https://bitbucket.org/snippets/Common_Admin/nr4aM) – kez Feb 26 '16 at 08:35
  • @shu I need to get these selected month and value to post action , is that possible to do in your approch – kez Feb 26 '16 at 09:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104625/discussion-between-shu-and-kez). – shu Feb 26 '16 at 10:32
  • Hi @shu in your first method to retrieve month, once I select value and click submit , then I check model values , I can see value for month property getting as 1 to 12 not as January to December , How can I get the string value , not the integer value ? – kez Feb 29 '16 at 03:48
  • @kez in `ViewBag.Months` make the `Value` same as `Text` and make the `SelectedMonth property as string` – shu Feb 29 '16 at 03:53