How to populate a textbox based on dropdown selection in MVC..?

后端 未结 1 1510
感动是毒
感动是毒 2021-01-15 06:35

Hi I have created a table and connected it to MVC project through ADO.NET entity. After connecting I added the controller for the entity and it creates a set of cshtml file

相关标签:
1条回答
  • 2021-01-15 07:26

    Firstly, let's create a View Model to hold these things:

    public class PlanViewModel
    {
        public List<SelectListItem> Plans { get; set; }
    }
    

    Then, in your controller action let's build the Model:

    public ActionResult Index()
    {
        var model = new PlanViewModel();
    
        model.Plans = db.Plan_S
            .Select(p => new SelectListItem
            {
                Value = p.Hours,
                Text = p.PlanNames
            })
            .ToList();
    
            return View(model);
        }
    

    Then in your View, do:

    @model Pivot.Models.Plan_S
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <div>   
        @Html.DropDownList("PlanNames", Model.Plans, "--select--")
        <input id="planHours" type="text" />
    </div>
    

    Then you'll need to do the following in jQuery:

    <script type="text/javascript">
        $(function () {
            $("[name='PlanNames']").change(function () {
                $("#planHours").val($(this).val());
            });
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题