How to set selected item in dropdownlist using LINQ? - c#

Currently my code is selecting the first item in the list. I want it to select the item which matches the MakeModelTypeCode.
E.G.
The selected item in the dropdownlist should be where this code
vehicleViewModel.VehicleDTO.VehicleDetails.MakeModelTypeCode
= MakeModelTypeCode from x
Here is the relevant code from the Business Logic class:
vehicleViewModel.AvailableMakeModels = GetAllMakeModelTypesForClient(selectedClientId);
vehicleViewModel.AvailableMakeModels = vehicleViewModel.AvailableMakeModels.GroupBy(x => x.ModelDescription).Select(x => x.First()).Distinct().ToList();
var vehicleMakeList = vehicleViewModel.AvailableMakeModels
.Select(s =>
new SelectListItem
{
Selected = true,
Text = s.MakeDescription,
Value = s.MakeModelTypeCode
});
Here is the relevant code from the .cshtml:
<div class="col-sm-6">
#Html.LabelFor(m => m.VehicleDTO.VehicleDetails.MakeDescription)
#Html.DropDownListFor(x => x.SelectedvendorText, new SelectList(Model.AvailableMakesSelectList, "Value", "Text", "Make"), new { #class = "form-control uppercase", #id = "ddlAvailableMakes", name = "ddlAvailableMakes", #onchange = "FillModels()" })
#Html.ValidationMessageFor(m => m.SelectedMake, "", new { #class = "text-danger" })
</div>
Here is the code from the Controller:
[Route("Edit-{id}")]
[Authorize]
public ActionResult Edit(string id)
{
VehicleViewModel vehicleViewModel = new VehicleViewModel();
selectedClientId = HelperMethods.GetClientId();
vehicleViewModel.VehicleDTO = this.vehicleBusinessLogic.GetClientVehicleDTO(id, this.selectedClientId);
vehicleViewModel = this.vehicleBusinessLogic.SetUpUpdateVehicle(vehicleViewModel, selectedClientId);
vehicleViewModel.VehicleDTO.VehicleDetails.ClientID = this.selectedClientId;
return View(vehicleViewModel);
}
I have tried a few different ways but can't get any to work. I can get just the item I want returned but not all the items + the selected item.
I was thinking I could do a nested Where clause inside the Select but that doesn't seem to work, but maybe my syntax was in-correct.

How about
MakeModelTypeCode toBeSelected;
var vehicleMakeList = vehicleViewModel.AvailableMakeModels
.Select(s =>
new SelectListItem
{
Selected = s.MakeModelTypeCode == toBeSelected,
Text = s.MakeDescription,
Value = s.MakeModelTypeCode
});

Changing the .cshtml to the below resolved the issue.
The only change was to replace x => x.SelectedvendorText with m => m.VehicleDTO.VehicleDetails.MakeModelTypeCode
<div class="col-sm-6">
#Html.LabelFor(m => m.VehicleDTO.VehicleDetails.MakeDescription)
#Html.DropDownListFor(m => m.VehicleDTO.VehicleDetails.MakeModelTypeCode, new SelectList(Model.AvailableMakesSelectList, "Value", "Text", "Make"), new { #class = "form-control uppercase", #id = "ddlAvailableMakes", name = "ddlAvailableMakes", #onchange = "FillModels()" })
#Html.ValidationMessageFor(m => m.SelectedMake, "", new { #class = "text-danger" })
</div>

Related

Cannot convert from 'System.Web.Mvc.SelectList' to 'string' so my Item Id is shown

In my ItemController, I have:
public ActionResult Index1()
{
ItemViewModel objItemViewModel = new ItemViewModel();
objItemViewModel.ListItemId = (from objItem in objShopOnlineDBEntities.Items
select new SelectListItem()
{
Value = objItem.ItemId.ToString(),
Selected = true
});
return View(objItemViewModel);
}
and to show in the view :
<div class="col-md-4">
<div class="form-group">
Item Id :
#Html.TextBoxFor(model => model.ItemId, new SelectList(Model.ListItemId, "Value", "Text" ), new { #class = "form-control"})
</div>
</div>
It doesn't let me show the item id. I have similar thing but for Category ID and I have selected the value of the category id 1 and to show me the name of that category id for example Men. That works just fine, but for id I can't get it to work.
You should use #Html.DropDownListFor() but not #Html.TextBoxFor()
#Html.DropDownListFor(model => model.ItemId,
new SelectList(Model.ListItemId, "Value", "Text" ),
new { #class = "form-control"})
While in your controller, you miss out the Text property for the SeletListItem.
objItemViewModel.ListItemId = (from objItem in objShopOnlineDBEntities.Items
select new SelectListItem()
{
Text = "<Item Text>",
Value = objItem.ItemId.ToString(),
Selected = true
})
.ToList();

How to get fieldname from SQL Server DB using the field ID

In my views, I have a few drop-down lists that I use to get the ID and show the value to the user so they know what they are choosing. But in the view that I use to list everything that has already been added, it shows the chosen ID, but I want the name to appear
I tried this but it always shows the status that has the ID 1, which is the status "Active"
#Html.DropDownListFor(modelItem => item.status,
(SelectList)ViewBag.listStatus,
new { #class disabled = "" })
//controller
{
public ActionResult listStatus()
{
var list= ListsDAO.listStatus();
return View(list);
}
}
//DAO
{
public static IEnumerable<LISTS> listStatus()
{
using (var ctx = new PadraoEntities())
{
var result= from lists in ctx.LISTS
where lists.TYPE_LIST== "STATUS"
select new
{
lists.IDE_LIST,
lists.DES_LIST,
lists.VLR_LIST
};
var list= new List<LISTS>();
foreach (var item in result)
{
list.Add(new LISTS()
{
IDE_LIST = item.IDE_LIST,
VLR_LIST = item.VLR_LIST,
DES_LIST = item.DES_LIST
});
}
return list;
}
}
}
//view add
<div class="form-group">
#Html.LabelFor(model => model.status, htmlAttributes: new { #class = "control -Label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.status(SelectList)ViewBag.listStatus, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.status, "", new { #class = "text-danger" })
</div>
</div>
//view list
{
#Html.DropDownListFor(modelItem => item.ststus,(SelectList)ViewBag.listStatus,new { disabled = "" })
}
when listing id 1, I expected "active" to appear, id 2 shows "inactive", etc
Try this //controller
public ActionResult listStatus()
{
ViewBag.Status = new SelectList(//Code to get id and its property, "StatusId", "Status");
var list= ListsDAO.listStatus();
return View(list);
}
//View
<div class="form-group">
#Html.LabelFor(model => model.Status, "TaskId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Status", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>

How to keep the id from the selectlist when using multiple columns in the textfield

I am trying to show multiple columns from my database in a dropdownlist using a SelectList
public ActionResult Create()
{
var times = db.Show_Courses
.Select(x =>
new {
id = x.show_course_id,
times = x.show_course_before + "," + x.show_course_after
});
ViewBag.course_id = new SelectList(times, "id", "times");
return View();
}
It shows up properly in the view but in the database the value of the id is 0
This was my code before i wanted to show two columns in the textfield of the selectlist
public ActionResult Create()
{
ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
return View();
}
And here is my code in the view
<div class="form-group">
#Html.LabelFor(model => model.course_show_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.course_show_id, "", new { #class = "text-danger" })
</div>
</div>
So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?
You could generate SelectList manually.
For example,
ViewBag.course_id = db.Show_Courses
.Select(x => new SelectListItem {
Text = x.show_course_before + "," + x.show_course_after,
Value = x.show_course_id.ToString() })
.ToList();
I personally like to use strongly type model. You can read more here
Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:
#Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })

Retrieve all item in listbox and select only those which is in db

Using first method I'm setting default subjects in listbox and using second I'm retrieving only these who was selected.
public void SubjectsList()
{
ViewBag.Subjects =
new SelectList(new[] { "Math", "Physic", "English" }
.Select(x => new { value = x, text = x }),
"Value", "Text");
}
public void SubjectsFromDb(int id)
{
var students = _db.Subjects.AsEnumerable().Where(x => x.StudentId == id).Select(q => new SelectListItem
{
Value = q.Name,
Text = q.Name,
}).ToList();
ViewBag.Subjects = students;
}
How can I do that in Listbox was all Subject but selected were only these which is in db?
Here's my listbox
<div class="form-group">
#Html.LabelFor(model => model.Subject, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.Subject,
new MultiSelectList((IEnumerable<SelectListItem>)ViewBag.Subjects, "Value", "Text"),
new { style = "display:block;" })
#Html.ValidationMessageFor(model => model.Subject)
</div>
</div>
Your model property Subject needs to be public IEnumerable<string> Subject { get; set; } although I would suggest it be renamed to Subjects - plural) and you rename the ViewBag property
The in the GET method, assign the existing subjects to the model
var model = yourModel()
{
Subjects = _db.Subjects.Where(x => x.StudentId == id).Select(q => q.Name);
};
ViewBag.SubjectList = new SelectList(new[] { "Math", "Physic", "English" });
return View(model);
Then in the view its
#Html.ListBoxFor(m => m.Subjects, (SelectList)ViewBag.SubjectList)
Side notes:
There is no need for the extra overhead of creating anonymous
objects to generate the SelectList - you can delete .Select(x => new { value = x, text = x }), "Value", "Text")
Since its already a SelectList, there is no need for the extra
overhead of creating another duplicate SelectList in the
ListBoxFor() method

JQuery not auto populating field elements with data

I have the following code:
#Html.TextBoxFor(x => x.Name, new { #onload = "if(this.value=='')this.value='NAME';", #class = "text", #onblur = "if(this.value=='')this.value='NAME';", #onfocus = "if(this.value=='NAME')this.value='';" })
#Html.TextBoxFor(x => x.Email, new { #onload = "if(this.value=='')this.value='EMAIL ADDRESS';", #class = "text", #onblur = "if(this.value=='')this.value='EMAIL ADDRESS';", #onfocus = "if(this.value=='EMAIL ADDRESS')this.value='';" })
But it only says 'NAME' when the box is clicked on, I want it to be there to begin with.
Why not just use the HTML5 placeholder attribute? That seems to be what you're trying to do.
#Html.TextBoxFor(x => x.Name, new { placeholder = "NAME" })
#Html.TextBoxFor(x => x.Email, new { placeholder = "EMAIL ADDRESS" })
You can use the attribute of HTML5 placeholder and the plugin jquery-placeholder for compatibility with other browsers
Html + Razor:
#Html.TextBoxFor(x => x.Name, new { placeholder = "NAME", #class="with-placeholder" })
#Html.TextBoxFor(x => x.Email, new { placeholder = "EMAIL ADDRESS", #class="with-placeholder"})
JS:
$('.with-placeholder').placeholder();
Data from: html5please.com

Categories