I have the folloiwng code inside my asp.net mvc action method:-
var CustomerData = customerlist.Select(m => new SelectListItem()
{
Text = m.SDOrganization.NAME,
Value = m.SDOrganization.ORG_ID.ToString(),
});
currently if i remove the ToString() from the ORG_ID , i will get an error that "can not explicitly convert long to string". so it seems that i have to define both the value and the text for the SelectListItem as strings. but since the SelectListItem should hold long , so is there a way to pass the values of the SelectListItem as long instead of strings?
...so is there a way to pass the values of the SelectListItem as long instead of strings?
No. And it doesn't make any sense to do so as when it is rendered, it's just HTML which has no concept of long.
If we have the action
public ActionResult Test()
{
var dictionary = new Dictionary<int, string>
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" }
};
ViewBag.SelectList = new SelectList(dictionary, "Key", "Value");
return this.View();
}
and the following view "Test.cshtml":
#using (Html.BeginForm())
{
#Html.DropDownList("id", ((SelectList)ViewBag.SelectList), "All")
<input type="submit" value="Go" />
}
The generated HTML is
<form action="/home/test" method="post">
<select id="id" name="id">
<option value="">All</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="submit" value="Go">
</form>
and when we post to this action, text of your number is effectively parsed back into your desired type by the Model Binder
[HttpPost]
public ActionResult Test(int? id)
{
var selectedValue = id.HasValue ? id.ToString() : "All";
return Content(String.Format("You selected '{0}'", selectedValue));
}
And the above works as you might expect.
Related
Form returns url format: localhost2343/index?Colors=red&Colors=blue&Colors=pink
asp-route return url format: localhost2343/index?Colors=red,blue,pink
If I use form submit button than everything seems good. But If i click on sort hyperlink than it will pass URL Colors=System.String%5B%5D
How can I pass value of Colors inside asp-route?
<form asp-page="./index" method="get">
<select asp-for="Colors" asp-items="#Model.Colors_SELECT" class="MultiSelect" multiple>
<option value="">All</option>
</select>
...
</form>
<Table>
...
<a asp-page="./Index" method="get"
asp-route-SortOrder="#Model.Colors_Sort"
asp-route-SearchString="#Model.SearchString"
asp-route-Colors="#Model.Colors">
#Html.DisplayNameFor(model =>
model.MyList[0].Colors)
</a>
...
</table>
[BindProperty(SupportsGet = true)]
public string[]? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }
public async Task OnGetAsync()
{
// Form - URL Format
// get values from URL & set inside selectlist
var result = Request.Query["Colors"];
var i = 0;
foreach (string? item in result) {
Colors[i] = item;
i++;
}
}
Update - I tried this but on sort link, it removes Sort variable & it picks only 1 Colors (not multi)
<a asp-page="./Index" method="get"
asp-route-SortOrder="#Model.Colors_Sort"
asp-all-route-data="#Model.routeData">
[BindProperty(SupportsGet = true)]
public Dictionary<string, string> routeData { get; set; }
....
var routeData = new Dictionary<string, string>();
routeData.Add("SortOrder", CurrentSort);
routeData.Add("SearchString", SearchString);
for (int i = 0; i < result.Count; i++)
{
var myParam = result[i];
routeData.Add($"Colors{i}", myParam.ToString());
}
This may help:
To get the selected values from a select element in a Razor page, you can use the Request.Form["selectName"] collection.
For example, consider the following select element:
#page "{Colors}"
<form method="post">
<select multiple name="colors">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
<button type="submit" asp-page-handler="GetColors">Submit</button>
</form>
To get the selected values in the form submission handler and modify the query string in the URL and include the selected values (red, blue, pink), you can try the following code:
public IActionResult OnGet(string? Colors)
{
if (string.IsNullOrWhiteSpace(Colors))
{
// do something
return Page();
}
if (!string.IsNullOrWhiteSpace(Colors))
{
// Do something
return Page();
}
return Page();
}
public IActionResult OnPostGetColors()
{
IDictionary<string, string> params = new Dictionary<string, string>();
var selectedColors = string.Join(",", Request.Form["colors"]);
params.Add("Colors", selectedColors);
string query = "";
foreach (var p in params)
query += $"{p.Key}={p.Value}";
var url = $"{HttpContext.Request.Path}?{query}";
return Redirect(url); // url : https://localhost:7272/index?Colors=red,blue,pink
}
This code will help you submit the selected values through the URL as a query string, and then will redirect the user to a new URL with the selected values added to the query string as multiple values for the colors parameter.
So I have the following scenario in which I am using two ViewBag(s):
To get the select list item
To get the particular item in concern
So it looks like this:
var currentType = "2";
List<SelectListItem> contentData = new List<SelectListItem>();
contentData.Add(new SelectListItem
{
Text = "Show 0 only",
Value = "0",
});
contentData.Add(new SelectListItem
{
Text = "Show 2 Only",
Value = "2",
});
ViewBag.currentType = currentType;
ViewBag.contentData = contentData;
Now in my Razor View, I am able to generate the DropDownList like this:
#Html.DropDownList("ContentTypeId", (IEnumerable<SelectListItem>)ViewBag.contentData, null, new { #class = "form-control" , #style = "width: 150px;" })
How can I can bind my ViewBag.currentType on the drop down list so it shows the pre selected value by default when the component is rendered?
Is it even possible to use two ViewBag value in this component ?
I tried like this:
#Html.DropDownList("ContentTypeId", (IEnumerable<SelectListItem>)ViewBag.contentData, null, new { #class = "form-control" , #style = "width: 150px;", #selected= (string)ViewBag.currentType})
But not getting the correct output.
Any tips/suggestions/solutions?
ViewBag is not working in your case, you will have to select an option manually, using Selected=true. HtmlDropDown is an outdated helper too.
Using html5 select with an asp helper is the best way to select item automatically
view
#{
var currentType = "2";
List<SelectListItem> contentData = new List<SelectListItem>();
contentData.Add(new SelectListItem
{
Text = "Show 0 only",
Value = "0",
});
contentData.Add(new SelectListItem
{
Text = "Show 2 Only",
Value = "2",
});
//or I guess you can take the from viewbag
string currentType = ViewBag.currentType;
List<SelectListItem> contentData = ViewBag.currentData
}
.....
<select class="form-control" id="levels" asp-for="#currentType"
asp-items="#contentData">
<option value="0" > Select </option>
</select>
this is working for dropdown list
#{
currentType = ViewBag.currentType;
contentData = ViewBag.contentData;
var dropDownItems = new SelectList(contentData,"Value","Text", currentType);
}
.....
#Html.DropDownList("#currentType",#dropDownItems,"Select",new { #class = "form-control" })
The SelectListItem Class has a Selected property.
You can just do :
List<SelectListItem> contentData = new List<SelectListItem>{
new SelectListItem
{
Text = "Show 0 only",
Value = "0",
},
new SelectListItem
{
Text = "Show 2 Only",
Value = "2",
Selected = true
});
I also wanted to post an answer with the attempt that I had made on this aspect and was able to achieve. I used the standard way of defining the pure HTML element instead of using the Razor helper tags. You can do this if you have dynamic elements which are not a part of your Model:
<select class="form-control" id="ContentDataId" name="ContentDataId">
#foreach (SelectListItem option in ViewBag.contentData as List<SelectListItem>)
{
<option value="#option.Value" #(option.Value == Convert.ToString(ViewBag.currentType) ? "selected='selected'" : "")>#option.Text</option>
}
</select>
The above definition will generate the same HTML if you used the helper tags. For those who have confusion using the helper tags, this is a more conventional way of generating your drop down list with dynamic ViewBag.
Title states what I'm trying to do.
Controller method:
public IActionResult Create()
{
IEnumerable<string> hList = from char s in _context.NR_Users select s.ToString();
List < NR_User > hUsers = new List<NR_User>();
hUsers = (from c in _context.NR_Users select c).ToList();
hUsers.Insert(0, new NR_User { ID = 0, Name = "Select" });
ViewBag.historyUsers = hUsers;
List<SelectListItem> options = new()
{
new SelectListItem { Value = "True", Text = "Yes" },
new SelectListItem { Value = "False", Text = "No" }
};
ViewBag.options = options;
return View();
}
View:
<div class="form-group col-md-4">
<label class="control-label">History PM</label>
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#ViewBag.historyUsers"></select>
<span asp-validation-for="History_PM" class="text-danger"></span>
</div>
But when I run the app and navigate to the Create page I get this error:
RuntimeBinderException: Cannot implicitly convert type 'System.Collections.Generic.List<EnvApp.Models.DB.NR_User>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)
I understand that it can't implicitly convert the list to an IEnumerable, but how exactly do I do that?
You can convert the list using SelectList class.
Try replacing
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#ViewBag.historyUsers"></select>
with
<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="#(new SelectList(ViewBag.historyUsers, "ID", "Name"))"></select>
I want to send the selected text field in dropdown to the controller.
When I use the code as follows, I can send the id number to the controllers, but the value I selected in the list pass null.
In addition , if there is a registered value in the model, I want this field to be selected in the dropdownlist when the page is opened.
Controller
public ActionResult Degerlendir(int id ,string CV_STATU)
{
using (MULAKATDBEntities1 ent = new MULAKATDBEntities1())
{
CvViewModel cv = new CvViewModel();
var entData = ent.CV.FirstOrDefault(a => a.ID_CV == id);
entData.CV_STATU = CV_STATU;
ent.SaveChanges();
}
}
In View
#using (Html.BeginForm("Degerlendir", "Home", FormMethod.Post))
{
<input type="hidden" name="id" value="#Model.Cv.ID_CV" />
#Html.DropDownListFor(model => model.Cv.CV_STATU,
new List<SelectListItem> {
new SelectListItem() { Text = "Secilmedi" },
new SelectListItem() { Text = "Kabul edildi" },
new SelectListItem() { Text = "Reddedildi" } },
new {#id="cv_statu", #class = "form-control" })
<input type="submit" id="btnSubmit" value="KAYDET" class="btn btn-add" />
}
Set #name="cv_statu" within the HTML helper htmlAttributes for binding to parameters on POST like this.
Also change the controller method parameter to lowercase cv_statu. Only parameter names passed through URL routes are not case sensitive.
I am assuming that what you shared on your code for your ActionResult is already the HttpPost Action verb. There should be a proper HttpGet as well.
To solve your issue, make sure the first argument that you set on your DropDownListFor should match on the parameter of your Degerlendir
#Html.DropDownListFor(model => model.CV_STATU,
new List<SelectListItem> {
new SelectListItem() { Text = "Secilmedi", Value = "Secilmedi" },
new SelectListItem() { Text = "Kabul edildi", Value = "Secilmedi" },
new SelectListItem() { Text = "Reddedildi", Value = "Reddedildi", Selected = true} }, "Please select an option",
new {#id="cv_statu", #class = "form-control" })
As you notice, I changed your:
#Html.DropDownListFor(model => model.Cv.CV_STATU
To:
#Html.DropDownListFor(model => model.CV_STATU
Because what you set here will set the name attribute on your HTML. This will be binded on your parameter on your ActionResult of Degerlendir particularly your parameter:
string CV_STATU
Lastly, I added Value on your SelectListItem, because that will be passed on your ActionResult whatever you select on your DropDownList. To set the default selected value, just add Selected = true.
For a Dropdown (as a SelectList) in my View, I can successfully set the value to the Id returned by my model, but the list does not update to reflect the selected Id as the selected item.
<%var type = Model.CompanyTypeId; %>
<%= Html.DropDownList("Type", (ViewData["Types"] as SelectList),
new Dictionary<string, object>()
{
{ "class", "form-control form-input"},
{ "Id", "CoType"},
{ "Name", "CoType"},
{ "value", type },
{ "option", "selected" }
})%>
I expect the dropdown list to update the selected item to the corresponding Id
(In ChromeDev tools I can verify the Id=Model.CompanyTypeId and option="selected", but the dropdown list still shows the item selected by default.
I expect the dropdown list to update the selected item to the corresponding Id
(In ChromeDev tools I can verify the Id=Model.CompanyTypeId and option="selected", but the dropdown list still shows the item selected by default.
<select id="CoType" name="CoType" class="form-control form-input"
option="selected" value="1">
<option value="-1">- Assign Type - </option>
<option value="1">Dummy</option>
<option value="2">Test CompanyType</option>
</select>
Since you already have Model.CompanyTypeId, you can easily use Html.DropDownListFor. You don't set value on the HTML attributes.
Controller
public ActionResult Index()
{
var model = new TestModel
{
CompanyTypeId = 1
};
ViewBag.Types = new List<SelectListItem>
{
new SelectListItem { Value = "-1", Text = "-- Assign Type --" },
new SelectListItem { Value = "1", Text = "Dummy" },
new SelectListItem { Value = "2", Text = "Test" },
};
return View(model);
}
View
#Html.DropDownListFor(m => m.CompanyTypeId,
(ViewBag.Types as List<SelectListItem>),
new Dictionary<string, object>()
{
{ "class", "form-control form-input"},
{ "Id", "CoType"},
{ "Name", "CoType"}
})