Value default with thymleaf in a combobox - html

I have a problem with thymleaf. I have a form with a combobox and some fields. I want put default value in the combobox and the clausure "selected" not working for me.
The code is this:
<select class="dsp-inline form-control" th:field="*{tipoDocumento}" required="required" th:disabled="${permisoXestion == false}">
<option value="" th:text="#{select.option.default}"> </option>
<option th:each="row : ${tipoDocumento}" th:value="${row}" th:text="#{${row.value}}" th:selected="#{${row==2}}"></option>
</select>
Where "tipoDocumento" is a enum with two values:
public enum TipoDocumento {
PUBLICO("documento.tipo.publico"),
PRIVADO("documento.tipo.privado");
private String property;
private String value;
private TipoDocumento(String property) {
this(property, null);
}
private TipoDocumento(String value, String property) {
this.value = value;
this.property = property;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
Can someone help me?

The selected tag should work. Remember it need to be added like selected="selected". I have used it on several selects and it always work. Also, in your th:each you need to remove the th:selected="#{${row==2}}" element, otherwise your first option won't be the default one.
<select class="dsp-inline form-control" required="required" th:disabled="${permisoXestion == false}">
<option value="" th:text="#{select.option.default}"></option>
<option th:each="row, iter : ${tipoDocumento}" th:value="${row}" th:text="#{${row.value}}" th:selected="${iter.count eq 2} ? 'selected' : 'false'"></option>
</select>

if you use the th:selected you cannot not use the th:field. You have to replace it with a name attribute.
So, can you replace
<select class="dsp-inline form-control" th:field="*{tipoDocumento}" required="required" th:disabled="${permisoXestion == false}">
with
<select class="dsp-inline form-control" name="tipoDocumento" required="required" th:disabled="${permisoXestion == false}">
Also, the condition of the th:selected
can you replace
th:selected="#{${row==2}}"
with
th:selected="${row==2}"

Related

MultiSelectList displaying only one selected value out of Selectedvalues

For httppost method MultiSelectList shows only one value in view side.
My view
<div class="col-md-6 form-group">
<select class="form-control selectpicker" required="" asp-for="DomID" asp-items=" ViewBag.DomList as MultiSelectList" multiple data-live-search="true"
placeholder="Select Categories"
onchange="console.log($(this).children(':selected').length)">
</select>
</div>
MY Controller
[HttpPost]
public IActionResult controllerAction([Bind]LogModel logmodel)
{
logmodel.selectedvals= // Has Submitted/selected values
List<LogModel> domList = new List<LogModel>();
domList = ;//getting values for dropdown
ViewBag.DomList = new MultiSelectList(domList , "DomID", "Dom", logmodel.selectedvals);
return view(logmodel);
}
My dropdown shows only one value selected from out of all selected values i.e.. from
logmodel.selectedvals in post action.
If I set hardcode selected values in httpget method for multiselectlist then it's shows
selected values properly. What I'm doing wrong here?
Updated
Log Model
public Int64 DomID { get; set; }
public string Dom { get; set; }
public List<Int64> selectedvals { get; set; }
Try to remove logmodel from return view(logmodel);
Below is a work demo, you can refer to it , hope it can help.
In Controller:
public IActionResult SetList()
{
return View();
}
[HttpPost]
public IActionResult ShowMList(LogModel logmodel)
{
List<LogModel> domList = new List<LogModel>();
domList.Add(new LogModel() { DomID = 1, Dom = "AA" });
domList.Add(new LogModel() { DomID = 2, Dom = "BB" });
domList.Add(new LogModel() { DomID = 3, Dom = "CC" });
ViewBag.DomList = new MultiSelectList(domList, "DomID", "Dom", logmodel.selectedvals);
return View();
}
SetList.cshtml:
#model LogModel
<form asp-action="ShowMList">
<select name="selectedvals" class="form-control" multiple>
<option value="1">AA</option>
<option value="2">BB</option>
<option value="3">CC</option>
</select>
<input type="submit" value="submit" />
</form>
ShowMList.cshtml:
#model LogModel
<div class="col-md-6 form-group">
<select class="form-control selectpicker" required="" asp-for="DomID" asp-items=" ViewBag.DomList as MultiSelectList" multiple data-live-search="true"
placeholder="Select Categories"
onchange="console.log($(this).children(':selected').length)">
</select>
</div>
result:
In aspfor int was using int instead of <int>

How to give a range in search in html and ASP.NET Core

I get data from database using SQL in ASP.NET Core. I can search area and price just giving the number but now I have to give range like 10 to 20 or etc. In search a web site zameen.com in which it exactly match with my requirements. But I do not know how to do this.
This is what I want:
My view:
<input list="Input.area.list"asp-for="Input.area" placeholder="Please Select area" style="height :50px; border-style:solid ;border-color: black;border-radius:5px; margin-left:20px;">
<datalist id="Input.area.list">
<option value="10"></option>
<option value="12"></option>
<option value="15"></option>
<option value="20"></option>
<option value="25"></option>
<option value="30"></option>
<option value="35"></option>
<option value="40"></option>
<option value="45"></option>
<option value="50"></option>
<option value="55"></option>
</datalist>
</input>
Controller:
public IActionResult Rent(inputModel input, int PageNumber = 1)
{
var data = rdb.GetDataHouse();
var datas = rdb.GetDataHouse();
ViewBag.Data = datas.ToList().Take(7);
ViewBag.Totalpages = Math.Ceiling(data.Count() / 6.0);
if (!string.IsNullOrEmpty(input.areaunit))
{
data = data.Where(x => x.areaUnit == input.areaunit & x.area <= input.area & x.price <= input.price).ToList();
}
data = data.Skip((PageNumber - 1) * 6).Take(6).ToList();
var viewModel = new RentModel
{
Data = data,
//SearchList = List<string>(),
Input = new inputModel(),
};
return View(viewModel);
}
Demo:
Here is a simple demo about it, Hope it can give you some help:
Model:
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Area { get; set; }
}
public class TestViewModel
{
[Required(ErrorMessage ="Please select a min value")]
public string min { get; set; }
[Required(ErrorMessage = "Please select a max value")]
public string max { get; set; }
}
Action:
public IActionResult Range()
{
List<SelectListItem> test = new List<SelectListItem>();
//generate some options for use to select
test.Add(new SelectListItem { Text = "10 ", Value = "10 " });
test.Add(new SelectListItem { Text = "20 ", Value = "20 " });
test.Add(new SelectListItem { Text = "30 ", Value = "30 " });
test.Add(new SelectListItem { Text = "40 ", Value = "40 " });
test.Add(new SelectListItem { Text = "50 ", Value = "50 " });
test.Add(new SelectListItem { Text = "60 ", Value = "60 " });
ViewBag.data = test;
return View();
}
[HttpPost]
public IActionResult Range(TestViewModel model)
{
var result = _dbContext.testModels.Where(x => x.Area >= Int32.Parse(model.min) && x.Area<= Int32.Parse(model.max)).ToList();
//....code......
return View();
}
View:
#model TestViewModel
<form method="post">
<h1>Please select a Range for Area</h1>
<div class="form-group">
<label asp-for="min" class="control-label"></label>
<select asp-for="#Model.min" asp-items="#ViewBag.data">
<option value="">Please select a value</option>
</select>
<span asp-validation-for="min" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="max" class="control-label"></label>
<select asp-for="#Model.max" asp-items="#ViewBag.data" placeholder="Please Select area">
<option value="">Please select a value</option>
</select>
<span asp-validation-for="max" class="text-danger"></span>
</div>
<button type="submit">Submit</button>
</form>
#section Scripts {
#{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
Demo:
Note:
You also need to set the maximum value in the drop-down list cannot be less than or equal to the minimum value. You can use javascript or fluent validation to achieve it.

Blazor/Razor: InputSelect with Enum?

How can I use the values of an enum class as options for an InputSelect?
Example enum:
public enum Test
{
Test1,
Test2
}
I am using with Blazor with Razor components.
Here's a working sample how to use enum in InputSelect component:
<EditForm EditContext="#EditContext">
<DataAnnotationsValidator />
<div class="form-group">
<label for="name">Enter your Name: </label>
<InputText Id="name" Class="form-control" #bind-Value="#comment.Name"></InputText>
<ValidationMessage For="#(() => comment.Name)" />
</div>
<div class="form-group">
<label for="body">Select your country: </label>
<InputSelect #bind-Value="#comment.Country" >
#foreach (var country in Enum.GetValues(typeof(Country)))
{
<option value="#country">#country</option>
}
</InputSelect>
<ValidationMessage For="#(() => comment.Country)" />
</div>
<p>
<button type="submit">Submit</button>
</p>
</EditForm>
#code
{
private EditContext EditContext;
private Comment comment = new Comment();
protected override void OnInitialized()
{
EditContext = new EditContext(comment);
base.OnInitialized();
}
public enum Country
{
USA = 1,
Britain,
Germany,
Israel
}
public class Comment
{
public string Name { get; set; }
public Country Country { get; set; }
}
}
Hope this helps...
So in short it's like this:
<InputSelect #bind-Value="#YourEnum">
#foreach (var value in Enum.GetValues<YourEnumType>()) {
<option value="#value">#value</option>
}
</InputSelect>
#enet answer is correct.
To add to this, sometimes enum values won't accept specific chars. you can edit the display of enum value to display specific chars in the code if you have filtered or changed enum values to store correctly. like below in my enum i replace all spaces with underscore. so you can add this to the code to display the enum values on the dropdown correctly.
<InputSelect #bind-Value="#updateUserDetails.Nationality" class="dropDownSelectList">
#foreach (var countryName in Enum.GetValues(typeof(Nationality)))
{
<option value="#countryName">#(#countryName.ToString().Replace("_", " ").Replace("HH", "-"))</option>
}
</InputSelect>
<select>
#foreach (var Item in Enum.GetValues(typeof( DayOfWeek)))
{
<option value="#Item">#Item</option>
}

how to receive html check box value in spring mvc controller

The problem is if the check box is not checked request can not find the correct mapping function in springMVC controller.Because it seems like it only send true values if it is checked,but it does not send false value if it not checked.
<form action="editCustomer" method="post">
<input type="checkbox" name="checkboxName"/>
</form>
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue[0])
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
I solved a similar problem specifying required = false in #RequestMapping.
In this way the parameter checkboxValue will be set to null if the checkbox is not checked in the form or to "on" if checked.
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam(value = "checkboxName", required = false) String checkboxValue) {
if (checkboxValue != null) {
System.out.println("checkbox is checked");
} else {
System.out.println("checkbox is not checked");
}
}
Hope this could help somebody :)
I had the same problem and I finally found a simple solution.
Just add a default value to false and it will work out perfectly.
Html code :
<form action="path" method="post">
<input type="checkbox" name="checkbox"/>
</form>
Java code :
#RequestMapping(
path = "/path",
method = RequestMethod.POST
)
public String addDevice(#RequestParam(defaultValue = "false") boolean checkbox) {
if (checkbox) {
// do something if checkbox is checked
}
return "view";
}
I had to add hidden input with same name of the checkbox. Value must be "checked".Then I can check the length of the string array within controller or in my service class.
<form action="editCustomer" method="post">
<input type="hidden" name="checkboxName" value="checked">
<input type="checkbox" name="checkboxName"/>
</form>
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue.length==2)
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
I think the proper answers are Paolo's and Phoste's ones.
ITOH, if you have many checkboxes/params/lasrge forms you can use a Map<T,T> RequestParam, so if the property does not exists - Map.get() return null - the checkbox is not checked.
#RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(#RequestParam Map<String,String> params)
{
String checkboxValue = map.get("checkboxName");
if(checkboxValue != null)
{
System.out.println("checkbox is checked");
return;
}
System.out.println("checkbox is not checked");
}

MVC Razor get option value from select with FormCollection

My view has a Select with elements(options) from my ViewModel.
#using (Html.BeginForm("NewUser", "Admin"))
{
<select multiple="" id="inputRole" class="form-control" size="6" name="inputRole">
#foreach (var item in Model.roller)
{
<option>#item.Name</option>
}
</select>
}
How can i get the selected value in my Controller?
[HttpPost]
public ActionResult NewUser(FormCollection formCollection)
{
String roleValue1 = formCollection.Get("inputRole");
}
This gives me a null value.
Try this to get the value of control in the formcollection
formCollection["inputRole"]
Your code becomes
[HttpPost]
public ActionResult NewUser(FormCollection formCollection)
{
String roleValue1 = formCollection["inputRole"];
}
You can simply accesss your form field by its name in that way
String role = formCollection["inputRole"];