I have a drop down and elements shown in UI in order of appearance
Footer
Header
Blabla
I want the dropdown to show Header at the top position in UI.
Header
Footer
Blabla
Code UI:
<select id="simTextEditorSelection" onchange="ShowTextEditorBasedOnSelection();" style="float:right;">
#foreach (PageInfoMV anItemForEditor in Model.ItemContents)
{
<option value="#anItemForEditor.ItemId">#anItemForEditor.ItemDisplayText</option>
}
Can I somehow mention in the code above to show a particular ID as default (TOP Position).
Model.ItemContents:
public List<PageInfoMV> ItemContents
{
get
{
if (this.itemContents == null) { this.itemContents = new List<PageInfoMV>(); }
if (!this.itemContents.Any(x => x.ItemId == Constants.HEADER_ID))
{
this.itemContents.Add(new PageInfoMV() { ItemId = Constants.HEADER_ID, ItemDisplayText = Constants.HEADER_DISPLAY_TEXT });
}
if (!this.itemContents.Any(x => x.ItemId == Constants.FOOTER_ID))
{
this.itemContents.Add(new PageInfoMV() { ItemId = Constants.FOOTER_ID, ItemDisplayText = Constants.FOOTER_DISPLAY_TEXT });
}
return this.itemContents;
}
set { this.itemContents = value; }
}
Constants.cs
public static readonly string HEADER_ID = "-1000";
public static readonly string FOOTER_ID = "-1001";
Its just a code snippet. If any more code chunk is required please do let me know. Thanks.
if your Header option value is constant then you should set on top your header.
<select id="simTextEditorSelection">
<option value="Footer">Footer</option>
<option value="Header"> Header</option>
<option value="Blabla">Blabla</option>
</select>
<script>
var val1=$("#simTextEditorSelection").find('option:eq(0)').val();
$('#simTextEditorSelection option[value="Header"]').insertBefore('#simTextEditorSelectionoption[value="'+val1+'"]');
</script>
var val1=$("#simTextEditorSelection").find('option:eq(0)').val();
$('#simTextEditorSelection option[value="Header"]').insertBefore('#simTextEditorSelection option[value="'+val1+'"]');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="simTextEditorSelection">
<option value="Footer">Footer</option>
<option value="Header"> Header</option>
<option value="Blabla">Blabla</option>
</select>
If you have control over ItemContents I would suggest adding an arbitrary value to rank your contents value; For example header would be 0, footer would be 1 etc. You can then use this to do an OrderBy() in your view:
#foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderBy(ic => ic.OrderValue))
{
...
}
EDIT:
Optional additional ordering for remaining items:
#foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderBy(ic => ic.OrderValue)
.ThenBy(ic => ic.SomeOtherValueMaybeName))
{
...
}
Related
In ASP.NET Core MVC, I'm trying to set the pre-selected value for a SelectList - something which I thought would be a simple task, but it's driving me bonkers!
My controller contains the following:
ViewData["Scores"] = GetScoresAsSelectList();
and
private SelectList GetScoresAsSelectList()
{
var scores =
Enumerable.Range(0, 6)
.Select(score => new
{
Value = score.ToString(),
Text = Helper.ConvertScoreToText(score) // gets some unique text back
})
.OrderBy(o => o.Value)
.ToList();
scores.Insert(0, new { Value = string.Empty, Text = "Please select a value" });
return new SelectList(scores, "Value", "Text", scores.FirstOrDefault().Value);
}
My view contains:
#{ var FieldScoreId = Guid.NewGuid(); }
<div class="form-group col-md-3">
<label asp-for="FieldScore" class="control-label"></label>
<select asp-for="FieldScore" class="form-control" asp-items="ViewBag.Scores" id="#FieldScoreId"></select>
<span asp-validation-for="FieldScore" class="text-danger"></span>
</div>
The output (rendered HTML) is:
<select class="form-control" id="1fce2ac1-e63c-4b85-b69a-14b7713eafaf" data-val="true" data-val-range="The field Field Score must be between 0 and 5." data-val-range-max="5" data-val-range-min="0" data-val-required="The Field Score field is required." name="FieldScore">
<option value="">Please select a value</option>
<option selected="selected" value="0">None (0)</option> <!-- WHY (OH WHY!?) IS THIS SELECTED? -->
<option value="1">1-Score (1)</option>
<option value="2">2-Score (2)</option>
<option value="3">3-Score (3)</option>
<option value="4">4-Score (4)</option>
<option value="5">5-Score (5)</option>
</select>
I've tried replacing scores.FirstOrDefault().Value with "". If Enumerable.Range(0, 6) was replaced with Enumerable.Range(1, 6) (start the range at 1, not 0), Please select a value would be selected.
I cannot figure out what the problem is, and it's driving me insane! :)
Many thanks for your help
Thank you to #JohnathanBarclay for leading me down the right path.
I changed my controller to the following:
private SelectList GetScoresAsSelectList()
{
var scores =
Enumerable.Range(0, 6)
.Select(score => new
{
Value = score, //changed from string to int
Text = Helper.ConvertScoreToText(score) // gets some unique text back
})
.OrderBy(o => o.Value)
.ToList();
scores.Insert(0, new { Value = -1/* changed from "" to -1 */, Text = "Please select a value" });
return new SelectList(scores, "Value", "Text", scores.FirstOrDefault().Value);
}
Also in the controller, in the Add GET method, I set FieldScore to -1. Works well: the dropdown defaults to "please select" and the dropdown has to be changed from "please select" as the model requires a range between 0 and 5.
I'm trying to insert data to a table which has a foreign key in it. I've put the categories in a select tag, shows them correctly, but when I try to pass that ID string to SelectedSubCatCategory, it shows up as null.
<select #bind="SelectedSubCatCategory">
#foreach (var item in category_items)
{
<option value="#item.Cat_ID" >#item.Cat_Name </option>
}
</select>
string SelectedSubCatCategory;
protected async Task SubCategoryInsert()
{
Guid guid = Guid.NewGuid();
string SubCatGUID = guid.ToString();
var category = await categoryService.GetEntryByIdAsync(SelectedSubCatCategory);
SubCategory sc = new SubCategory()
{
SCat_ID = SubCatGUID,
SCat_Cat = category,
SCat_Name = SelectedSubCatName
};
await subCategoryService.InsertEntryAsync(sc);
}
I figured it out on my own:
You have to have an #onchange event instead of #bind
<select #onchange="SetSelectedSubCatCategory">
<option> Please select </option> // default option
#foreach (var item in category_items)
{
<option value="#item.Cat_ID" >#item.Cat_Name </option>
}
</select>
And then this little code will do the rest
void SetSelectedSubCatCategory(ChangeEventArgs e)
{
SelectedSubCatCategory = e.Value.ToString();
}
gg ez
I have a dropdownlist in edit view that has a value from the database. What I want to do is to display the saved value in separate dropdown list. For example, I have saved two different data in database with same foreign key to determine that these two records are treated as one. (See below sample image)
https://imgur.com/ex57YTO
I am only using single-selection dropdown list and I am only looping the count of records to determine how many dropdown list to display in the edit page. So if I have "No harm event" and "Complaints" events, this must be displayed in separate dropdown list because what I did now is they are both displaying in one dropdown list so the result is it looks like the record is duplicated (see image below) but actually these two records are in each of the dropdown list.
https://imgur.com/YlVZHWx
https://imgur.com/FXYO4Tn
VIEW
//for loop to count records that will determine how many dropdown list to be displayed
#for (var i = 0; i < Model.SavedEventsToList.Where(a => a.incidentReportId == Model.IRId).Count(); i++)
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId) //this is the foreign key that determine these two records are as one
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
</div>
</td>
</tr>
}
CONTROLLER
public ActionResult Edit(Guid? id)
{
IMRBusinessLogic imrLogic = new IMRBusinessLogic();
var imrRepo = new IMRRepository();
IMRDTO imr = imrRepo.GetIRDetailsForEdit(id);
imr.SavedEventsToList = imrLogic.SavedEvents(id);
return View(imr);
}
public List<PSESavedEventsDTO> SavedEvents(Guid? incidentReportId)
{
using (IREntities db = new IREntities())
{
var events = (from a in db.SavedPatientSafetyEvents(incidentReportId)
select new PSESavedEventsDTO
{
pseSavedEventId = a.pse_saved_event_category_and_subcategory_id,
pseEventsId = a.pse_events_id,
pseEventsName = a.pse_events_name,
seqNum = a.seq_num,
incidentReportId = a.incident_report_id,
savedRowIndex = a.saved_row_index,
selected = a.selected
}).ToList();
return events;
}
}
I need to separate them so the user can still have an option to edit each of these two records.
This is the expected output I need: https://imgur.com/uwVjvkz
Can someone help me with this.
Thank you in advance.
I already found the solution in this. I just use foreach instead of for loop, and I get the desired output I need.
#foreach (var index in Model.SavedEventsToList.Where(a => a.savedRowIndex != 0))
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId && item.savedRowIndex == index.savedRowIndex)
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
<span title="Patient Safety Events Description" class="input-group-addon" data-toggle="popover" data-container="body" data-placement="right" data-trigger="hover" data-html="true" href="#" id="login"><i class="fa fa-info-circle"></i></span>
</div>
</td>
</tr>
}
I have a Blazor app that populates 6 select option dropdowns with data from DB. Three of these are populated with date and time from a string list.
When I select a date and time it is not displayed in the dropdown box. After selecting a date time the dropdown is blank, but the value is actually selected and binding works. It's just not displayed.
If I remove "bind=#..." it displays correctly.
Have anyone else experienced this, and how did you solve it?
<select bind="#Innput.Klokkeslett1">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1">#tid1</option>
}
</select>
Two things to note, select uses a string value, and that value needs to match the option value.
So, if your field Innput.Klokkeslett1 is a DateTime, you will need to use a property to handle the binding / conversion between string and DateTime.
If you ensure you use an explicit date format for the option values, and your property returns it's value in the same date format, then the select will be able to match it's value to one of it's option values and display the corresponding text, which can be formatted any way you like.
<select bind="#MySelectProxy">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1.ToString("yyyy-MM-dd HH:mm:ss")">#tid1</option>
}
</select>
#functions
{
string MySelectProxy {
get => Innput.Klokkeslett1.ToString("yyyy-MM-dd HH:mm:ss");
set => DateTime.TryParse(value, out Innput.Klokkeslett1);
}
}
<select onchange="#ComboSelectionChanged">
<option value="0" selected>
#list[0]
</option>
#for (int i = 1; i < list.Count; i++)
{
<option value="#i">
#list[i]
</option>
}
</select>
public void ComboSelectionChanged(UIChangeEventArgs e)
{
if (int.TryParse(e.Value.ToString(), out int index))
{
SelectedStyleIndex = index
//now you know which one is selected
}
}
I have an list of objects that I receive in my Razor View in C#
#model IEnumerable<Project.Models.EvaluationObject>
In each object of the IEnumerable I have a property called "MaxValue" that I want to put selected in a input select of html.
foreach(var item in Model){
<select>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
<option value=4>Four</option>
</select>
}
For each item I want to build a select input with the value of the item.MaxValue selected
i.e. In the first loop item.MaxValue = 3, then I should build the next select:
<select>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3 selected="selected">Three</option>
<option value=4>Four</option>
</select>
The item.MaxValue is ever between 1 and 4, so If the value is 3 the selected value in the select input is 3.
The First solution I had, is to put an if statement in each option, but I think that's impractrical:
foreach(var item in Model){
<select>
<option value=1 #if(item.MaxValue==1){<text>selected="selected"</text>})>One</option>
<option value=2 #if(item.MaxValue==2){<text>selected="selected"</text>}>Two</option>
<option value=3 #if(item.MaxValue==3){<text>selected="selected"</text>}>Three</option>
<option value=4 #if(item.MaxValue==4){<text>selected="selected"</text>}>Four</option>
</select>
}
Hope you can help me, May be I should use some JavaScript.
You can add a IEnumerable<SelectListItem> to your model:
Model:
public class EvaluationObject
{
public IEnumerable<SelectListItem> EvaluationList
{
get
{
return Enumerable.Range(1, 4)
.Select(x => new SelectListItem
{
Selected = x == MaxValue,
Text = NumberToWord(x),
Value = x
});
}
}
public int MaxValue { get; set; }
public int EvaluationNumber { get; set; }
}
View:
foreach (var item in Model)
{
#Html.DropDownListFor(x => x.EvaluationNumber, item.EvaluationList)
}