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>
Related
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.
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>
}
I'm using ASP Core Razor pages.
This my Edit.cshtml.cs:
[BindProperty]
public List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> CCusers { get; set; }
and here I fill CCusers with data:
CCusers =new List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>() {
new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "1", Text = "HR", Selected = true },
new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "2", Text = "IT", Selected = false },
new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Value = "3", Text = "Account", Selected = false },
};
In Razor Page, I used two different select:
<select asp-for="CCusers" asp-items="#Model.CCusers" id="CCusers" multiple="multiple" class="selectpicker"> </select>
//and this:
#Html.DropDownList("NewSelect", Model.CCusers, new { #class = "selectpicker", #multiple = "multiple" })
and this the result of both of them:
<select id="CCusers" multiple="multiple" class="selectpicker" name="CCusers">
<option value="1">HR</option>
<option value="2">IT</option>
<option value="3">Account</option>
</select>
<select class="selectpicker" id="NewSelect" multiple="multiple" name="NewSelect">
<option selected="selected" value="1">HR</option>
<option value="2">IT</option>
<option value="3">Account</option>
</select>
The Core Select didn't set the selected item while the #Httml.DropDownList did it.
What I'm missing in the first select?
For Select Tag Helper, you will need to set asp-for which specifies the model proprety name for the select element.
For your issue, you need to define new property for selected CCusers instead of binding the CCusers to asp-for directly.
You could refer code below:
Page
public class EditModel : PageModel
{
[BindProperty]
public int[] SelectedCCuserIds { get; set; }
[BindProperty]
public List<SelectListItem> CCusers { get; set; }
public void OnGet()
{
SelectedCCuserIds = new int[] { 1, 2 };
CCusers = new List<SelectListItem>() {
new SelectListItem() { Value = "1", Text = "HR" },
new SelectListItem() { Value = "2", Text = "IT" },
new SelectListItem() { Value = "3", Text = "Account" },
};
}
public IActionResult OnPost()
{
var result = SelectedCCuserIds;
return RedirectToAction("OnGet");
}
}
View
#page
#model CoreRazor.Pages.EditModel
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form method="post">
<select asp-for="#Model.SelectedCCuserIds" asp-items="#Model.CCusers"
multiple="multiple" class="selectpicker"> </select>
#*#Html.DropDownList("NewSelect", Model.CCusers, new { #class = "selectpicker",
#multiple = "multiple" })*#
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default" />
</div>
I am quite new to ASP .Net, and could use some help... I have an ASP .Net Core 1.1 web app. In it, I have an "Edit" view for editing a simple object, which a corresponding controller calls when routed to it. This is the view:
#model InspectionsTestClient.Models.Property
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
#Html.ValidationSummary();
<form asp-action="Edit">
<div class="form-horizontal">
<h4>Property</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="UnitNumber" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UnitNumber" class="form-control" />
<span asp-validation-for="UnitNumber" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="BuildingName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="BuildingName" class="form-control" />
<span asp-validation-for="BuildingName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Street" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Street" class="form-control" />
<span asp-validation-for="Street" class="text-danger"></span>
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is the controller which calls that view:
// GET: Property/Edit/5
public ActionResult Edit(int id)
{
return View();
}
And this is the model:
namespace InspectionsTestClient.Models
{
//[Table("property")]
public class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
[MaxLength(10, ErrorMessage = "Unit number too long")]
[Display(Name = "Unit #")]
public string UnitNumber { get; set; }
[MaxLength(45, ErrorMessage = "BuildingName name too long")]
public string BuildingName { get; set; }
[MaxLength(45, ErrorMessage = "Street too long")]
public string Street { get; set; }
}
}
So when I navigate to that page, the controller fires up, and returns the Edit view. I have confirmed the parameter "id" is populated. When the Edit view loads in the browser, however, all the input textboxes are empty. I would expect them to be pre-populated with the values for the object in question. What am I missing?
The issue you are experiencing is happening because you are not returning that object to the view.. actually in your case you're not even going out to the db to get the object.
You need to edit you Edit action to something like this:
// GET: Property/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var object = db.TableName.Find(id);
// db = connectionstring
// TableName = database table that holds the object that you want to return
if (object == null)
{
return HttpNotFound();
}
return View(object);
}
Let me know if this helps
public class PropertyController
{
private readonly ApplicationDbContext _dbContext;
public PropertyController(ApplicationDbContext dbContext){
_dbContext = dbContext;
}
//GET: Property/Edit/5
public async Task<IActionResult> Edit(int id)
{
var property = await _dbContext.Property.FirstOrDefaultAsync(p => p.Id == id);
return View(property);
}
}
If you don't pull the data from the database and send it to the view of course it will always be blank. Edit(int id) there will be 2, both slightly different from the other.
[HttpPost]
[ValidateAntiForgeryToken]
//Post: Property/Edit/5
public async Task<IActionResult> Edit(int id, [Bind("Id", "UnitNumber", "BuildingNumber", "Street")] Property property)
{
if(ModelState.IsValid){
}
else{
}
}
not everyting is present but that is part of your adventure.
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"];