0

In few places in my MVC football application I'm using order by using the same column, but just in one place it works wrong and I'm not sure why.

Here's my Round model:

public class Round : IValidatableObject
{

    public int RoundID { get; set; }
    public int RoundNumber { get; set; }
    public DateTime RoundStart { get; set; }
    public DateTime RoundEnd { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

And my Match model:

public class Match
{

    public int MatchId { get; set; }
    public string HomeClubName { get; set; }
    public string AwayClubName { get; set; }

    public virtual Club HomeClub { get; set; }
    public virtual Club AwayClub { get; set; }

    public int? Club1Goals { get; set; }
    public int? Club2Goals { get; set; }

    [Required]
    public int RoundNumber { get; set; }

    [ForeignKey("RoundNumber")]
    [InverseProperty("Matches")]
    public virtual Round Round { get; set; }
}

I'm ordering by column RoundNumber from class Round. It works on my whole project like this:

return View(db.Round.ToList().OrderBy(s => s.RoundNumber));

And it works like a charm. However in one place it works wrong. It's in the list of matches (every match has a round number). Here's the code for this:

public ActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        if (isAdminUser())
        {
            return View(db.Round.ToList().OrderBy(s => s.RoundNumber));
        }
        else return RedirectToAction("Index", "Home");
    }
    else
    {
        ViewBag.Name = "Not Logged IN";
    }
    return View(db.Round.ToList().OrderBy(s => s.RoundNumber));
}

I have a feeling it might be sorting by RoundI rather than RoundNumber as I added the rounds in the following order:

20, 21, 22, 23, 24, 25, 19, 18, 1, 3, 33, 32, 11

to test my theory and that's the order they appear in this particular view (I want to sort matches by their round numbers). Here's the code for creating a new match:

[Authorize]
public ActionResult Create()
{
    if (isAdminUser())
    {
        ViewBag.RoundNumber = new SelectList(db.Round.OrderBy(s => s.RoundNumber), "RoundID", "RoundNumber");
        ViewBag.AwayClubName = new SelectList(db.Clubs, "ClubName", "ClubName");
        ViewBag.HomeClubName = new SelectList(db.Clubs, "ClubName", "ClubName");
        return View();
    }
    else return RedirectToAction("Index", "Matches1");
}

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "MatchId,HomeClubName,AwayClubName,Club1Goals,Club2Goals,RoundNumber")] Models.Match match)
{
    if (isAdminUser())
    {
        if (ModelState.IsValid)
        {
            if (match.HomeClubName.Equals(match.AwayClubName))
            {
                ViewBag.RoundNumber = new SelectList(db.Round.OrderBy(s => s.RoundNumber), "RoundID", "RoundNumber", match.RoundNumber);
                ViewBag.AwayClubName = new SelectList(db.Clubs, "ClubName", "ClubName", match.AwayClubName);
                ViewBag.HomeClubName = new SelectList(db.Clubs, "ClubName", "ClubName", match.HomeClubName);
                return View(match);
            }
            db.Match.Add(match);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.RoundNumber = new SelectList(db.Round.OrderBy(s => s.RoundNumber), "RoundID", "RoundNumber", match.RoundNumber);
        ViewBag.AwayClubName = new SelectList(db.Clubs, "ClubName", "ClubName", match.AwayClubName);
        ViewBag.HomeClubName = new SelectList(db.Clubs, "ClubName", "ClubName", match.HomeClubName);
        return View(match);
    }
    else return RedirectToAction("Index", "Matches1");
}

And it's view:

@model ProjSty3Exp.Models.Match
@{
    ViewBag.Title = "Add";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="main_bg">
    <div class="wrap">
        <div class="sap_tabs">
            <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;">
                <div class="tekst" style="font-size: 1em; color: #d9d9d9; display: block; line-height:1.5em; margin-left: 5%">
                    <br />
                    @Html.Raw(ViewBag.Error)
                    <br />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        @Html.LabelFor(model => model.HomeClubName, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                           @Html.DropDownList("HomeClubName", null, htmlAttributes: new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.HomeClubName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <br />
                    <div class="form-group">
                        @Html.LabelFor(model => model.AwayClubName, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                           @Html.DropDownList("AwayClubName", null, htmlAttributes: new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.AwayClubName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <br />
                    <div class="form-group">
                        Numer kolejki:
                        <div class="col-md-10">
                            @Html.DropDownList("RoundNumber", null, htmlAttributes: new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.RoundNumber, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <br />
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Dodaj mecz" class="btn btn-default" />
                        </div>
                    </div>
                    <br />
                    <div>
                        @Html.ActionLink("Powrót do panelu administratora", "Index", "Admin")
                    </div>
                </div>
                <br />
            </div>
        </div>
    </div>
</div>
}

Is it creating a new match that breaks it? RoundNumber is int and not string, so it's not alphanumeric sorting problem. It also sorts right when displaying list of rounds alone or in dropdownlist when creating a match.

Why does it sort by RoundId (probably) and not RoundNumber here?
If anyone has any idea what is going on or how to fix it, I'd appreciate it a lot.

Mus.K
  • 3
  • 3
  • Why is the FK in `Match` to `RoundNumber` instead of `RoundID`? (surely `RoundID` is the PK of `Round`). And not related, but `.ToList()` in `db.Round.ToList().OrderBy(..)` is unnecessary –  Jan 18 '17 at 01:09
  • @StephenMuecke The RoundNumbers can't be repeated as well, should I change the FK to RoundId even if every RoundNumber has to be different? Also thank you for the toList tip, I'll fix that. Any idea why my sorting behaves like this? – Mus.K Jan 18 '17 at 01:13
  • I assume because your `@Html.DropDownList("RoundNumber", ...)` is selecting a `RoundID` value (your `ViewBag.RoundNumber(..)` code sets the option values based on property `RoundId` but then your FK is to `RoundNumber`, not `RoundID` –  Jan 18 '17 at 01:26
  • But there is an awful lot of bad practice in your code with respect to your dropdownlists and I suggest you read the following - [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) and [Will there be any conflict if i specify the viewBag name to be equal to the model property name ...](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557). Use a view model, and include `IEnumerable` properties for your SelectLists –  Jan 18 '17 at 01:28
  • @StephenMuecke I had problem with dropdownlists and that's what someone here advised me to do. Works good, didn't know it's a bad practice. I'll read the links right now. Thank you a lot for helping me! – Mus.K Jan 18 '17 at 01:35

0 Answers0