开发者

Count duplicates in C# MVC3 with View

开发者 https://www.devze.com 2023-03-31 17:58 出处:网络
I need a help of displaying the view of comodities, by excluding the duplicate, but adding quantity to the count

I need a help of displaying the view of comodities, by excluding the duplicate, but adding quantity to the count E.g.

Name   ComodityModel count  SellerName 
Iphone 3gs           1      Neal 
Iphone 4g            1      Jane 
Iphone 3gs           1      Neal 
Iphone 3gs           1      Jane

Output should be

Name   ComodityModel count  SellerName
Iphone 3gs          2       Neal 
Iphone 4g           1       Jane 
Iphone 3gs          1       Jane

I need to filter it by Comodity model and SellerName. I have database and model Comodity

public class Comodity
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Date is required")]
    //[DisplayFormat(DataFormatString = "{0:d}")]
    [DataType(DataType.Date)]
    public DateTime ? RegisterDate { get; set; }

    [Required(ErrorMessage = "Comodity Model must be specified")]    
    public string ComodityModel { get; set; }

    [Required(ErrorMessage = "Color must be specified")]
    [StringLength(15)]
    public string Color { get; set; }

    [Required(ErrorMessage = "Price Required")]
    [Range(1, 1000, ErrorMessage = "Price must be between $1 and $100")]
    [DisplayFormat(DataFormatString = "{0:c}")]
    public decimal Price { get; set; }

    [Required(ErrorMessage = "Seller name must be specified")]
    [StringLength(15)]
    public string SellerName { get; set; }

    public int CountCom { get; set; }
}

public class ComodityDBContext : DbContext 
{ 
    public DbSet<Comodity> Comodities { get; set; } 
}

and Controller where I defined Actionresult MyView

    public ActionResult MyView(DateTime? startDate, DateTime? endDate, string comModel, string searchString)
    {
        //   if (string.IsNullOrEmpty(comModel))
        //   {
                //     return View(comodities);
        //   }

        //   else
        //   {
           //    return View(comodities.Where(x => x.ComodityModel == comModel));
         //  }
        DateTime dtNow;
        dtNow = DateTime.Today;

        if (!startDate.HasValue)
        {
            startDate = new DateTime(dtNow.Year, dtNow.Month, 1);
            endDate = startDate.Value.AddMonths(1).AddDays(-1);
        }
        if (startDate.HasValue && !endDate.HasValue)
        {
            endDate = (new DateTime(startDate.Value.Year, startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);
        }


        ViewBag.startDate = startDate.Value.ToShortDateString();
        ViewBag.endDate = endDate.Value.ToShortDateString();

        var viewDate = from r in db.Comodities
                       where r.RegisterDate >= startDate.Value && r.RegisterDate <= endDate.Value == true
                       //  orderby r.RegisterDate
                       select r.RegisterDate;

        var SelectListName = new List<string>();
        var SelectNameQry = from m in db.Comodities
                            select m.SellerName;
        SelectListName.AddRange(SelectNameQry.Distinct());
        ViewBag.searchString = new SelectList(SelectListName);

        var comModelLst = new List<string>();
        var comModelQry = from d in db.Comodities
                          orderby d.ComodityModel
                          select d.ComodityModel;
        comModelLst.AddRange(comModelQry.Distinct());
        ViewBag.comModel = new SelectList(comModelLst);

        var comodities = from m in db.Comodities
                         select m;

        IDictionary<string, IList<string>> dict = new Dictionary<string, IList<string>>();
        var queryC = from c in db.Comodities
                     group c by c.ComodityModel into g
                     where g.Count() > 1
                     select new { ComodityModel = g.Key, CCount = g.Count() };
        foreach (var item in queryC)
        { // comodities = comodities.Where(item => item.Name && item => item.CCount);
            //View("", item.ComodityModel, item.CCount);
            //  ViewBag(item.ComodityModel, item.CCount);
            String key = item.ComodityModel;
            if (dict.ContainsKey(key))
            {
        // add the class name into an existing "string" collection
                 dict[key].Add(item.ComodityModel);
            }
            else
            {
        // instantiate a new "string" collection and add the class name.
                dict[key] = new List<string> { item.ComodityModel };
            }

            int maxCourseCount = 0;
             foreach (var k in dict.Keys)
            {
                int valueCount = dict[k].Count;
                if (valueCount > maxCourseCount)
                    maxCourseCount = valueCount;
            }
        }



        if (!String.IsNullOrEmpty(searchString))
        {
            comodities = comodities.Where(s => s.SellerName.Contains(searchString));
        }
        if (startDate.HasValue && endDate.HasValue)
        {
            comodities = comodities.Where(r => r.RegisterDate >= startDate.Value && r.RegisterDate <= endDate.Value);

        }

        if (string.IsNullOrEmpty(comModel))
        {
            return View(comodities);
        }

        else
        {
            return View(comodities.Where(x => x.ComodityModel == comModel));
        }
    }

I am new in MVC and have no idea how to count and make view. Please, help. Also, is there some suggestion about date picking. It is showing incorrectly. I assume that it only comparing the day, not whole day-month-year. Thanks in advance

Finally MyView

@model IEnumerable<SaleCenter.Models.Comodity>

@{
    ViewBag.Title = "total";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>开发者_JAVA技巧;
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<h2>total</h2>

<p>

    @using (Html.BeginForm()){          
        <p>  startdate:@Html.TextBox("startDate", null, new { @class = "datePicker" }) &nbsp;
             enddate : @Html.TextBox("endDate", null, new { @class = "datePicker" }) </p>
        <p>  model: @Html.DropDownList("comModel", "All") &nbsp; 
             seller: @Html.DropDownList("SearchString", "All")  
             <input type="submit" value="Total" /></p>    
    }
</p>
<table>
    <tr>
        <th>
            product name
        </th>
        <th>
            Model
        </th>
         <th>
            seller
        </th>
        <th>
            quantity
        </th>
        <th>
            graphic
        </th>
    </tr>

@foreach (var item in Model)
{
    int w = (int)(2000 * item.CountCom / 100); 
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ComodityModel)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SellerName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CountCom)
        </td>

      <td>
      <img src="@Url.Content("~/Content/Images/graph.gif")" width="@w.ToString()px" height="6px"  alt="" />

        </td>

    </tr>
}

</table>

<script type="text/javascript">
    $(document).ready(function () {

        $('.datePicker').datepicker({ firstDay: 1, dateFormat: 'dd.mm.yy', showOn: 'button',
            buttonImage: '/Content/images/calendar.gif',
            duration: 0
        });
    });
</script>


For showing the commodity and it's count in the view. Quick way it to create a anonymous object from your comodities by grouping with name and get it's count. Return this anonymous object as the model to the view.

Better approach is to create ViewModel specific to this purpose, so that you could create a tightly bound view.


Here is a method to plop into your ComodityController.cs file:

    private int getComodityCount(string param_Name, string param_ComodityModel, string param_SellerName)
    {
        return db.Comodity.Where(x => x.Name == param_Name && x.ComodityModel == param_ComodityModel && x.SellerName == param_SellerName).Count();
    }

Now, to get the number of duplicates within the Collection of Comodity you call:

    int count = getComodityCount("iPhone","3gs","Neal");

What's more, if you change the privacy setting from private to public, you can even call the method from your view like this:

Here is the method changed to public:

    public int getComodityCount(string param_Name, string param_ComodityModel, string param_SellerName)
    {
        return db.Comodity.Where(x => x.Name == param_Name && x.ComodityModel == param_ComodityModel && x.SellerName == param_SellerName).Count();
    }

and here is the code for your View:

    @{
        int count = new ComodityController().getComodityCount("iPhone","3gs","Neal");
    }

I hope this helps. The Where(linq) method is REALLY handy for database querying.

0

精彩评论

暂无评论...
验证码 换一张
取 消