I've got a DropdownListFor
that serves to hold a list of Tags. It is important to say that I will have 3 of these identical drop downs, as you can have up to 3 tags associated per request.
I am using the ViewModel method and would prefer to stay away from ViewBag
.
This is my view model. The tag list holds ALL tags. And the selected tags holds any current associated tags with the request object.
public class editRequestViewModel
{
public Request userRequest { get; set; }
public List<SelectListItem> Tags { get; set; }
public List<SelectListItem> SelectedTags { get; set; }
}
This is my controller specific to the tags.
public ActionResult Edit(int id)
{
try
{
if (ModelState.IsValid)
{
domainUser GetAllUsers = new domainUser();
using (var db = new DAL.HelpDeskContext())
{
var query = (from m in db.Requests
where m.ID == id
select new editRequestViewModel()
{
userRequest = m,
Tags = (from x in db.Tags
select new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList().OrderBy(x => x.Text).ToList(),
SelectedTags = (from x in db.AssociatedTags
join u in db.Tags on x.TID equals u.ID into cc
from c in cc.DefaultIfEmpty()
where x.RID == id
select new SelectListItem()
{
Text = c.Name,
Value = c.ID.ToString()
}).ToList().OrderBy(x => x.Text).ToList()
}).FirstOrDefault();
return View(query);
}
}
else
return View();
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "Change", "Browse"));
}
}
I have tried setting the value in the controller like this but it doesn't change the outcome. (15 is a possible ID for a tag)
query.SelectedTags[0].Value = "15";
And finally here is how I am using the drop down list in the View.
<div class="form-group">
@Html.Label("Tag One", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.DropDownListFor(model => model.SelectedTags[0].Value, Model.Tags, "Select Tag", new { @class = "form-control " })
</div>
</div>
Using the above code, the drop down list is defaulted to "Select Tag". Obviously if I have a value pulled into SelectedTags[0].Value
, I want that value to be the default value when the page is first loaded.
Something is telling me the way its indexed is the issue, but I cannot seem to figure out why. Since I have 3 select list item objects in my list, I should be able to just specify the index, correct?