unknown artist01
unknown artist01

Reputation: 3

ASP.NET Populating Dropdown with associated foreign key text value

I am very new to ASP.NET and I am currently struggling with binding my dropdown to the associated foreign key table.

My Controller

public ActionResult Create()
{
    //get current user id 
    ViewBag.UserID = new SelectList(db.UserProfiles, "UserID", "Employer");
    return View();
}

My View

<div class="form-group">
  @Html.LabelFor(model => model.UserID, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.DropDownList("UserID", null, htmlAttributes: new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.UserID, "", new { @class = "text-danger" })
  </div>
</div>

My DB Table

Database tables

My View on the browser

Browser view of the dropdown list

I have also created a login in order to know what user has logged in

[HttpPost]
public ActionResult Index(UserProfile log)
{
    var user = db.UserProfiles.Where(x => x.UserName == log.UserName && x.Password == log.Password).Count();
    if (user > 0)
    {
        return RedirectToAction("Create", "Dashboard");
    }

    else
    {
        return View();
    }
}

In conclusion on the dropdown list i would like to see the employer associated and therefore cascade it to the user based on the table relationship. I don't want to see the other employers if they are not related to the user that has logged in. What is the best way to achieve that?

Upvotes: 0

Views: 85

Answers (1)

Kavi
Kavi

Reputation: 140

When login is successful then pass the userid while redirecting to next page. Use that userid in the next page get the dropdown values from database(where userid=loggedinuserid). now you will get only emploees corresponding to the current user.

use session to store and use the userid in redirected page. or this link will help you. RedirectToAction with parameter

Upvotes: 1

Related Questions