topcool
topcool

Reputation: 2720

Asp.net core How to bind data and get value of select TagHelper?

Before everything look at my Model.

SystemPart Model

public class systemPart
{
   public int id { get; set; }
   public string systemName { get; set; }
   public int systemLevel { get; set; }
}

I want to use this model in Create view. also In create view i want to have a <select> TagHelper from the same Model.

Look at Create View

@model MyProject.Models.systemPart
<form asp-controller="SystemPart" asp-action="Create" method="post">


        <div class="form-group">
            <input asp-for="systemName" class="form-control" />
        </div>

        <div class="form-group">
            <select asp-for="systemName" asp-items="@(new SelectList(ViewBag.SysList,"id","systemName"))"  class="form-control"></select>
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-success" />
        </div>

    </form>

And in Controller I have :

   public class RoleController : Controller
   {
      private readonly ApplicationDbContext _context;
      public RoleController(ApplicationDbContext context)
      {
        _context = context;
      }

    [HttpGet]
    public IActionResult Create()
    {
        var sp = new List<systemPart>();
        sp = _context.sysPart_Tbl.ToList();
        ViewBag.SysList = sp;
        return View();
    }

    [HttpPost]
    public IActionResult Create(systemPart model)
    {
        if (ModelState.IsValid)
        {
            //
        }
        return View(model);
    }
   }

Now after lunch project DropDownList display info. But after select an option in DropDownList and submit form i cant get selected text and id.

At HttpPost action method, I want the amount of the selected value (selected id) assign to SystemLevel

Upvotes: 1

Views: 14443

Answers (1)

Mohammad Akbari
Mohammad Akbari

Reputation: 4776

change asp-for="systemName" to asp-for="SystemLevel"!

    <div class="form-group">
        <select asp-for="SystemLevel" asp-items="@(new SelectList(ViewBag.SysList,"id","systemName"))"  class="form-control"></select>
    </div>

Upvotes: 3

Related Questions