Saturday 11 February 2017

mvc get selected value and text from drop down list in controller

Watch on YouTUbe



Controller
        CompanyEntities db = new CompanyEntities();

        public ActionResult testDDL()
        {
            CustomerModel c;
            c = new CustomerModel
            {
                Comp = db.GetCompanies()
            };
            return View(c);
        }

        [HttpPost]
        public ActionResult testDDL(CustomerModel model)
        {
            int? SelectedID = model.SelectedCompanyID;
            string SelectedText = model.SelectedCompanyName;
            model.Comp = db.GetCompanies();
            return View(model);
        }


View
@model MVCDDLTest.Models.CustomerModel

@using(Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken();
    @Html.Hidden("SelectedCompany", Model.SelectedCompanyName)

    @Html.DropDownListFor(Model => Model.SelectedCompanyID, new SelectList(Model.Comp, "CompanyID", "CompanyName"), "Default Value", new { @id = "SelID" })
    <input type="submit" vaue="submit" />
}

@section Scripts{
   
    <script type="text/javascript">
        $(document).ready(function () {
            $("#SelID").change(function (evt) {
                $("#SelectedCompany").val($("#SelID option:selected").text().trim());
            });
        });
    </script>   
}


Model

     public class CustomerModel
    {
        public IEnumerable<GetCompanies_Result> Comp {get;set;}
        public int SelectedCompanyID { get; set; }
        public string SelectedCompanyName { get; set; }
        public string Test { get; set; }
    }

5 comments:

  1. Hello thank you for sharing the information but i didn't understand it
    public IEnumerable Comp {get;set;}
    what GetCompanies_Result ?

    ReplyDelete
    Replies
    1. I have the almost the same solution and could not get it working, if I have an dialog box / modal where I do edit and create new. Thats where I do the dropdown and its not working

      Delete
    2. This video explains how to get data from table using stored procedures - https://www.youtube.com/watch?v=HQlgQRvrqmk&feature=youtu.be

      Delete
  2. Hey bro, may i have your that source project ? if can you send to my email andretriputra87@gmail.com, thanks alot bro

    ReplyDelete
  3. Where is GetCompanies() method ??

    ReplyDelete