How to return select option value? - asp.net-mvc

This is my Html
<div class="form-row">
<div class="col-md-3">
<div class="position-relative form-group">
<label class="">Status</label>
<select class="form-control" id="txtStatus" name="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
</div>
</div>
</div>
how to do something like this is asp.net mvc?
<option value="A" <%if Status="A" then%>Selected
<%end if%>>Active</option>
<option value="I" <%if Status="I" then%>Selected
<%end if%>>Inactive</option>
#Model.Status is my value.
How to Do like this :
<option value="A" <%if #Model.Status="A" then%>Selected
<%end if%>>Active</option>

The proper way to do is to use the #Html.DropDownListFor helper method. In the Model we need to introduce a property for available statuses that can be selected.
public class ViewModel
{
public string Status { get;set;}
public IEnumerable<SelectListItem> Statuses { get;set;}
public ViewModel()
{
Statuses= new List<SelectListItem>
{
new SelectListItem {Text = "-- Select Status --", Value = ""},
new SelectListItem {Text = "Active", Value = "A"},
new SelectListItem {Text = "InActive", Value = "I"}
};
}
}
and in view then we can write :
#Html.DropDownListFor(x => x.Status, Model.Statuses,
new { #class ="form-control" , id ="txtStatus"})
It will generate html something similar to :
<select class="form-control" id="txtStatus" name="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
UPDATE:
You can do with plain html like:
<option value="A" #(Model.Status =="A" ? "selected" : "")>Active</option>
<option value="I" #(Model.Status =="I" ? "selected" : "")>Inactive</option>

Related

getting empty list inside IActionResult on button submit - razor pages partial view

I am trying to pass a list of ids to IActionResult on button submit. The ids are coming from dropdown list selections. My view is a partial-view getting a model object. the problem is right now when i submit, the list is empty always.
I have read that we can not pass a list to controller! then what are the possible approaches, I am literally stuck on this for a day!
I have only pasted part of the code i felt is necessary to show,
please let me know if you want to see other code.
View.cshtml
<form method="post" asp-page-handler="UpdateComponent">
.
.
.
#{
var value1 = 0;
var value2 = 0;
var value3 =0;
}
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_1 mt-2" data-search="true" asp-for="#value1">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_2 mt-2" data-search="true" asp-for="#value2">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select class="form-control Shoplist News-plant-select_3 mt-2" data-search="true" asp-for="#value3">
<option value="">Bitte auswählen</option>
</select>
#{
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value1 });
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value2 });
Model.newsletterSubComponents.Add(new Models.NewsletterSubComponents() { NewPlantArticleId = value3 });
}
<input type="hidden" name="value1" value="#Model.newsletterSubComponents" asp-for="#Model.newsletterSubComponents"/>
.
.
.
<input type="submit" value="Speichern" class="btn btn-primary" />
</form>
controller
public IActionResult OnPostUpdateComponent(NewsletterComponents component, int? newsId, int? shortArticleId,
List<NewsletterSubComponents> newsletterSubComponents, int? test)
{
^
|
list empty
.
.
.
}
i populate dropdown lists using ajax
$.ajax(settings).done(function (data) {
$.each(data, function (index, element) {
$('.News-plant-select_1').append($("<option>").val(element.Id).text(element.NameGerman));
console.log(element.NameGerman);
$('.News-plant-select_2').append($("<option>").val(element.Id).text(element.NameGerman));
console.log(element.NameGerman);
});;
//remove spinner
$('.News-plant-select').removeClass("spinner-border");
});
If you want to receive ids, I think you can just use List< int > to receive it, also keep the parameter name the same as that in select element. I made an example based on your codes:
<form method="post" asp-page-handler="UpdateComponent">
#{
List<NewsletterSubComponents> newsletterSubComponents = new List<NewsletterSubComponents>
{
new NewsletterSubComponents{ NewPlantArticleId = 1, NewPlantArticleName = "AAA"},
new NewsletterSubComponents{ NewPlantArticleId = 2, NewPlantArticleName = "BBB"},
new NewsletterSubComponents{ NewPlantArticleId = 3, NewPlantArticleName = "CCC"}
};
var selectList = new SelectList(newsletterSubComponents, "NewPlantArticleId", "NewPlantArticleName");
}
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_1 mt-2" data-search="true" asp-items="#selectList" >
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_2 mt-2" data-search="true" asp-items="#selectList">
<option value="">Bitte auswählen</option>
</select>
<br />
<!-- asp-items="New plant SelectList"-->
<select name="newsletterSubComponentIds" class="form-control Shoplist News-plant-select_3 mt-2" data-search="true" asp-items="#selectList">
<option value="">Bitte auswählen</option>
</select>
<input type="submit" value="Speichern" class="btn btn-primary" />
</form>
Result:

my tag helper Drop Down Select Will Not render properly in .NET core

<div class="form-group">
<label asp-for="roles" class="control-label"></label>
<select asp-for="roles" class="custom-select" asp-items="#(new Select List(ViewBag.Roles))">
<option value="">Assign Role</option>
</select>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px" asp-items="#(new Select List(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
</div>
my drop down in not responsive any help
how to make drop down responsive
It is possible that the value of ViewBag.Roles is assigned incorrectly. Here is an example.
In Index.cshtml
#{
ViewBag.Roles = new List<MyModel>
{
new MyModel{Id=1, Name="thisname"},
new MyModel{Id=2, Name="thisname2"},
};
}
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px"
asp-items="#(new SelectList(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
Here is the model.
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Result.

Select tag helper selected value not rendered in view

I need some help with my select tag helper.
I have an asp.net MVC View with a select 2 control as follows:
<div class="col-md-3">
<div class="form-group">
<label asp-for="NumberingType.Type" class="control-label" data-toggle="popover" data-placement="right" data-trigger="click" title="Field Help" data-content="Select the Numbering Scheme type that you want to create">Number Scheme Type *</label>
<select asp-for="NumberingType.TenantNumberingTypeId" asp-items="Model.NumberingType.NumberingTypeList" class="form-control select2">
<option></option>
</select>
<span asp-validation-for="NumberingType.TenantNumberingTypeId" class="text-danger"></span>
</div>
</div>
I am initialising the select2 as follows:
<script type="text/javascript">
$(document).ready(function () {
$(".select2").select2({
placeholder: "Select",
theme: 'bootstrap',
allowClear: true
});
});
</script>
I am loading the correct scripts:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
In my controller, I am populating the select 2 as follows:
public async Task<IActionResult> EditNumberScheme(int numberId)
{
var vm = new NumberingViewModel();
try
{
vm = await GetNumberingViewModel(numberId);
vm = UpdatedBaseViewModel<NumberingViewModel>(vm);
}
catch (Exception e)
{
await ErrorHandler.HandleException(e);
vm.MessageType = BaseViewModel.UserMessageType.Error;
}
return View(vm);
}
and
private async Task<NumberingViewModel> GetNumberingViewModel(int numberId)
{
var number = await DataGet.GetTenantNumberScheme(numberId);
NumberingViewModel model = new NumberingViewModel
{
Numbering = number
};
model.NumberingType = new TenantNumberingTypeModel();
model.NumberingType.NumberingTypeList = DataGet.GetTenantNumberingTypes().Result
.Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type, Selected = (x.TenantNumberingTypeId == number.TenantNumberingTypeId) })
.ToList();
model.Owner = await DataGet.GetTenantOwner(UserInfo.Instance.Tenant.TenantId);
return model;
}
The select2 values are successfully loaded from the database and the selected value shows in the controller.
When placing a breakpoint at the select in the View, it is clear that the selected value is set as true in the NumberingTypeList.
Model.NumberingType.NumberTypeList = Count = 4
[1] = {Microsoft.AspNetCore.Mvc.Rendering.SelectListItem}
Disabled = false
Group = null
Selected = true
Text = "Credit Note"
Value = "2"
However the selected value is not rendered in the view.
<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="The TenantNumberingTypeId field is required." id="NumberingType_TenantNumberingTypeId" name="NumberingType.TenantNumberingTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>
Any help will be appreciated
Thanks
I managed to get this working by following this tutorial https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper
It seems that the error is caused by the binding of the asp-for attribute. When I explicitly set the selected item in the controller as so:
model.NumberType = new TenantNumberingTypeModel();
model.NumberType.NumberSchemeList = DataGet.GetTenantNumberingTypes().Result
.Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type })
.ToList();
model.NumberingType.TenantNumberingTypeId = number.TenantNumberingTypeId;
number being the object retrieved from the database
then it works correctly and the asp-items automatically selects the value that is represented by the asp-for attribute.
<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="Please select a type" id="NumberType_NumberTypeId" name="NumberType.NumberTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option selected="selected" value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>
Hope this helps someone
That is the example of the visibility, you must use "select2.full.min.js".

changes to &nbsp in asp.net mvc html.dropdownlist

I want to show items with indention in html.dropdownlist
this is code in controller
IEnumerable<ViewModels.testvm> test = db.Database.SqlQuery<ViewModels.testvm>(#"WITH tree (id, parentid, level, title, rn) as
(
some code
)
***********SELECT id,REPLICATE(' ',level) + title as title
FROM tree
order by RN");
ViewBag.ParentID = new SelectList(test, "ID", "Title");
as you can see I add &nbsp to dropdown items in replecate
but the problem is &nbsp shows in dropdown.
this is view > source result:
<select class="form-control" id="ParentID" name="ParentID"><option
value="10">Menu1</option>
<option value="11">&nbsp;Sub1</option>
<option value="14">&nbsp;Submenu1</option>
<option value="12">Menu2</option>
<option value="16">&nbsp;sub2</option>
<option value="13">Menu3</option>
<option value="15">&nbsp;sub3</option>
<option value="17">&nbsp;&nbsp;sub sub</option>
<option value="22">&nbsp;&nbsp;&nbsp;sub3 sub sub</option>
<option value="19">menu4</option>
<option value="20">&nbsp;sub4</option>
<option value="21">menu5</option>
</select>
as you can see converted to &nbsp;
I tried "\xA0" instead of &nbsp but it shows in dropdown too!
I think html.raw can solve this, but I don't know how can I use it with html.dropdownlist.
this is view
<div class="col-md-10">
#Html.DropDownList( "ParentID", null, htmlAttributes: new { #class = "form-
control" })
</div>
any Idea?
Edit
by changing view like this the problem solved:
I tried this after checked a post as answer
<select class="form-control" id="ParentID" name="ParentID">
<option value="0">First Level</option>
#foreach (var item in ViewBag.ParentID)
{
<option value="#item.Value">#Html.Raw(#item.Text)</option>
}
</select>
You can manually create the dropdown list assuming you place your collection in a ViewModel member called ParentIDs:
The View:
#if (Model.ParentIDs.Any())
{
<select class="form-control" id="ParentID" name="ParentID">
#foreach (var item in Model.ParentIDs)
{
if (Model.ParentID == item.id)
{
<option value="#item.id" selected>#item.title</option>
}
else
{
<option value="#item.id">#item.title</option>
}
}
</select>
}

Razor encodes everything

Razor is encoding every unicode character. How to prevent that?
Example:
This is my Razor:
#Html.DropDownListFor(model => model.Category,
(IEnumerable<SelectListItem>) ViewBag.CategoriesList,
"موضوع صفحه را انتخاب کنید...", new{
#class = "form-control some-css"
})
And this the rendered html:
<select class="form-control some-css" id="Category" name="Category">
<option value="">
موضوع صفحه را انتخاب کنید...
</option>
<option value="SomeValue">
موزه
</option>
<!-- some other options -->
</select>
You could use Html.Raw()
#Html.DropDownListFor(model => model.Category,
(IEnumerable<SelectListItem>)ViewBag.CategoriesList,
Html.Raw("موضوع صفحه را انتخاب کنید..."), new
{
#class = "form-control some-css"
})

Resources