0

well , I am new to MVC5 and i have two issues and your help will be appreciated. the first one is :- have tow models one for voteadmin to set an election date and election id and one is for the employees i named it votingmodel, now we have already accepted the data of election from employees and i want to retrieve all the data when the election.id is equal to integer, for example 55. i have assigned to votingmodel electionDetails all the data like election id candidate name , employee name, estatus and other columns now i want to retrieve candidate name, date, reasonoforelecting, from the table for all rows containg the electionid 55

here is the model votingmodel

    public virtual int EmployeeId { get; set; }
    public virtual int ElectionId { get; set; }
    public virtual string ElectionName { get; set; }
    public virtual DateTime EEnd { get; set; }
    public virtual string CandidateName { get; set; }
    public virtual int Estatus { get; set; }
    public string EPosition { get; set; }
    public virtual string EDepartment { get; set; }
    public virtual string EDescription { get; set; }

i want to display in the table election id, name, estatus,department,position from all the rows table electiondetails when electionid =55 and see how many comments i have tried many methods but i couldnt get it

in the controller model i have

        public ActionResult Index() 
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(votingModel chk)
        {
            var id = chk.ElectionId;
            string ids = Convert.ToString(id);

            if (db.votingModels.Find(id) == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            //votingModel votingModel = db.votingModels.Find(id);
            if (id == null)
            {
                return HttpNotFound();
            }
            //var result = db.votingModels.Include("ElectionName").Where(p => p.ElectionId)
            //db.votingModels = db.votingModels.Contains(id)

            //model.Customers = db.Customers.OrderBy(
            //           m => m.CustomerID).Take(5).ToList();

            var query = from a in db.votingModel
                        where SqlFunctions.StringConvert((double)a.ElectionId).Contains(id)
                        select a;
            var item = query.FirstOrDefault();
            if (item != null)
            {
                return View(item);
            }
            else
            {
                return View("NotFound");  //Let's show a view about item not found
            }
            return View(votingModel);
        }

in the view model i have this code

    @model election.Models.votingModel

    @{
        ViewBag.Title = "index";
    }

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @*<p>
            @Html.ActionLink("Create New", "Create")
        </p>*@
        @Html.Label("election ID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.ElectionId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ElectionId, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="submit" class="btn btn-default" />
            </div>
        </div>
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.ElectionId)
        </dt>

    <dd>
        @Html.DisplayFor(model => model.ElectionId)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.ElectionName)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.ElectionName)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EStart)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EStart)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Estatus)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Estatus)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EPosition)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EPosition)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EDepartment)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EDepartment)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EDescription)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EDescription)
    </dd>

</dl>
}

the second issue is if i want to check of three conditions

i want to check if the employee has already voted
if electionid entered by the user exist in database andand employeedid is exist in same row andand estatus exist and = 2 means he already voted how can i make that condition. thanks all

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
Ebrahim
  • 3
  • 2
  • 8

2 Answers2

0

The Find method looks up an entity using its primary key. Because ElectionId in the VotingModel is a foreign key, you have to use a Where, Single or First clause to search by it.

The following code assumes that there is exactly one row in the votingModels table with the given ElectionId. If there are multiple matching rows, you would have to change this logic to use a Where instead of a Single, and your View must take @model election.Models.votingModel[].

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(votingModel chk) {

    // chk.ElectionId can never be null because this property is not nullable in VotingModel 
    long id = chk.ElectionId; 

    // assuming there is only a single entry with this ElectionId in the DB
    votingModel existing = db.votingModels.SingleOrDefault(v => v.ElectionId == id); 

    // SingleOrDefault returns null if no entry matches the condition
    if (existing == null) {
        return View("NotFound");
    }

    return View(existing);
}
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • thank you for the respond with answer, still i am getting error while using where statement votingModel existing = db.votingModels.Where(v => v.ElectionId == id); and i tired to add Tolist(); but i didnt get it done the error coming "Severity Code Description Project Suppression State File Line Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable' to 'election.Models.votingModel'. An explicit conversion exists (are you missing a cast?)" and i used list and Ilist select p; – Ebrahim May 18 '17 at 11:51
  • Yes, `Where` returns an `IEnumerable`, whereas `First` and `Single` return one instance of `T`. So the line should be `IEnumerable existing = db.votingModels.Where(v => v.ElectionId == id);` or just write `var` instead of `IEnumerable`. – Georg Patscheider May 18 '17 at 14:53
  • thank you Georg, finally the red color under the id is gone but another problem appears in the view model, if u got wat i need is to make the user enter the electionid and all rows having that id should be displayed, is it possible to do that with single view because now am getting this error in the view model, "CS1061: 'votingModel[]' does not contain a definition for 'ElectionId' and no extension method 'ElectionId' accepting a first argument of type 'votingModel[]' could be found (are you missing a using directive or an assembly reference?)", – Ebrahim May 18 '17 at 23:42
  • and i tried to change the view model to @model IEnumerable though same error is occurring "S1061: 'IEnumerable' does not contain a definition for 'ElectionId' and no extension method 'ElectionId' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) – Ebrahim May 18 '17 at 23:45
  • If you define the `@model` as a collection in the cshtml file, you have to loop over the individual entries using a `for`. See for example http://stackoverflow.com/questions/17037858/how-to-pass-ienumerable-list-to-controller-in-mvc-including-checkbox-state – Georg Patscheider May 19 '17 at 07:40
  • no benefits of doing that , i think it is not allowed to do with same view not sure – Ebrahim May 21 '17 at 06:25
0

you can not do both in same view accepting input and retrieving from database, what you can do make to views one getting the election-id from user pass it to controller if condition then show another view , make sure to use parameter to send the user input and do the validation hope that answers your question

Developer
  • 29
  • 11