Home > Mobile >  How can I set default value select tag without options .net core
How can I set default value select tag without options .net core

Time:09-30

How can I set a default value.I want to set a value for all users. For example, My default value will be "User" and users role will be "User" Here is my cshtml

  var roles = (List<IdentityRole>)ViewData["roles"];
  <div >
                <label asp-for="Input.UserRole"></label>
                <select asp-for="Input.UserRole"  asp-items='new SelectList(roles,"Id","Name")'>
                </select>
                <span asp-validation-for="Input.UserRole" ></span>
            </div>

I have property but I can't set default value from here it doesnt work.

public string UserRole { get; set; }
  var role = _roleManager.FindByIdAsync(Input.UserRole).Result;
   await _userManager.AddToRoleAsync(user, role.Name);

CodePudding user response:

add an option to select

<select asp-for="Input.UserRole"  asp- 
            items='new SelectList(roles,"Id","Name")'>
  
<option>Default Value</option>
                
</select>
        

CodePudding user response:

set default value select tag without options .net core

You can try to use ViewModel. Below is a demo, you can refer to it.

CreateLeaveRequestVM:

 public class CreateLeaveRequestVM
    {         
        public List<leaveTypes> LeaveTypes { get; set; } 
        public leaveTypes Selectedtype { get; set; }       
    }

leaveTypes:

public class leaveTypes
    {
        public int Id { get; set; } 
        public string Name { get; set; }    
    }

HomeController:

 public IActionResult Index()
        {
            var leaveTypes = new List<leaveTypes>()
            {   
                new leaveTypes{Id=1, Name="a"},
                new leaveTypes{Id=2, Name="b"}
            };
            var selected = new leaveTypes() { Id = 3, Name = "c" };
            leaveTypes.Add(selected);
            var model = new CreateLeaveRequestVM
            {
                LeaveTypes = leaveTypes,
                Selectedtype = selected
            };           
            return View(model);
         }

Index:

@model CreateLeaveRequestVM
<form method="post" asp-action="Index" >
<div >
                <label asp-for="Selectedtype.Id"></label>
                <select asp-for="Selectedtype.Id"   asp-items="@(new SelectList(Model.LeaveTypes,
 "Id", "Name"))">
                </select>
                <span asp-validation-for="Selectedtype.Id" ></span>
            </div>
            <button  type="submit">
                submit
            </button>
</form>

result:

enter image description here

  • Related