[RESOLVED]how to get selected text from dropdown in mvc5?

hi,

I am new to MVC.

I appended data to dropdownlist but i cant to get the selected item from dropdownlist( I did not used models i fetch the data using json in controller)

could any one guide me

how to to get selected (text/value) from dropdown in form post in mvc5

my code is:

HomeController:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace postbackevents.Controllers
{
    public class HomeController : Controller
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        List<SelectListItem> Colleges = new List<SelectListItem>();
        List<SelectListItem> subjects = new List<SelectListItem>();
        List<SelectListItem> students = new List<SelectListItem>();
      
        //
        // GET: /Home/
       
        public ActionResult Index()
        {
            ViewBag.var1 = getColleges();
            ViewBag.var2 = subjects;
            ViewBag.var3 = students;
            return View();
        }
       

        private SelectList getColleges()
        {
            using(SqlConnection con=new SqlConnection(constr) )
            {
                try
                {
                    con.Open();
                    SqlDataReader dr = null;
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "select Id,name from College";
                    cmd.Connection = con;
                    dr = cmd.ExecuteReader();
                    while(dr.Read())
                    {
                        Colleges.Add(new SelectListItem { Text = dr["name"].ToString(), Value = dr["Id"].ToString() });
                    }
                }
                catch(Exception ex)
                {
                    string msg = ex.Message;
                }
                return new SelectList(Colleges, "Value", "Text", "Id");
            }
        }
        public JsonResult getSubjects(int id)
        {

            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select * from subjects where CollegeId =" + id + " ", conn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {

                    subjects.Add(new SelectListItem { Text = myReader["subname"].ToString(), Value = myReader["id"].ToString() });
                }
            }
            return Json(subjects, JsonRequestBehavior.AllowGet);

        }

        public JsonResult getStudents(int id)
        {

            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select * from Students where SubId =" + id + " ", conn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {

                    students.Add(new SelectListItem { Text = myReader["StudentName"].ToString(), Value = myReader["Id"].ToString() });
                }
            }
            return Json(students, JsonRequestBehavior.AllowGet);

        }
	}
}

index.cshtml file:

@{
    ViewBag.Title = "Index";
}

<script src="../../Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
<h2>Index</h2>
Colleges @Html.DropDownList("var1","Select College")
Subjects          @Html.DropDownList("var2", "Choose")
Student          @Html.DropDownList("var3", "Choose")

<script type="text/javascript">
    $(function () {

        $("#var1").change(function () {
            var name = $("#var1 :selected").val();
            var url = 'Home/getSubjects';
            var data1 = { "id": name };
            $.post(url, data1, function (data) {
                var items = [];
                items.push("<option value=" + 0 + ">" + "Choose Subject" + "</option>");
                for (var i = 0; i < data.length; i++) {

                    items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
                }
                $("#var2").html(items.join(' '));
                $("#var3").empty();
                $("#var3").append("<option>choose</option>");

            })
        });

        $("#var2").change(function () {
            var name = $("#var2 :selected").val();
            var url = 'Home/getStudents';
            var data1 = { "id": name };
            $.post(url, data1, function (data) {
                var items = [];
                items.push("<option value=" + 0 + ">" + "Choose team" + "</option>");
                for (var i = 0; i < data.length; i++) {

                    items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
                }
                $("#var3").html(items.join(' '));


            })
        });
    });

        </script>
<form>
    <input type="submit" value="submit"  />
</form>

now i want when i click submit button

i want to show the output like

College=selected college Name

course=selected course name

student=selected student name

Thanks,

Murali.

you actually already have parts of that code.

$('#mysubmitbutton').click(function(e){
e.preventDefault(); var first = $("#var1 :selected").val(); var second = $("#var2 :selected").val(); var third = $("#var3 :selected").val(); // add your ajax post and give a json like { student : first, something : second, another : third } });

hope this helps a little

murali krishna14

now i want when i click submit button

i want to show the output like

College=selected college Name

course=selected course name

student=selected student name

Do you want to display this on the same view, or on the next view after you submit your form?

To simply display the selected item’s text, use:

// show school
$("#var1").text();

// show subject
$("#var2").text();

// show student
$("#var3").text();

Thanks sp00k,

I am a begineer

could you please post the code for this

 // add your ajax post and give a json like { student : first, something : second, another : third }

Hi John,

I want to return back those values to controller(action method)

based on those values i need to perform some calculations.

place the dropdowns and submit button on same form

@using(@Html.BeginForm("actionname","ControllerName",FormMethod.Post))
{
Colleges @Html.DropDownList("var1","Select College")
Subjects          @Html.DropDownList("var2", "Choose")
Student          @Html.DropDownList("var3", "Choose")

    <input type="submit" value="submit"  />
</form>
}

and write the action to post the values

[HttpPost]
public ActionResult SaveCylDetail(string var1,string var2,string var3)
{

}

Hi Murali,

First, if you can’t get the data in the action, please modify the code like this:

var data1 =JSON.stringify({ "id": name });

Secondly, to display the selected data, please refer to this code below:

$('#mysubmitbutton').click(function(e){
    e.preventDefault();
    var first = $("#var1 :selected").val();
    var second = $("#var2 :selected").val();
    var third = $("#var3 :selected").val();
    var result="";
    result=result+"College="+first+"n";
   result=result+"course="+second +"n";
result=result+"student="+third +"n";
alert(result);
   $("#targetDiv").val(result);
  });

Best Regards

Starain

murali krishna14

could you please post the code for this

here’s a sample post

        $.post(
            '@Url.Action("Edit", "PriceList")',
            { Id: id, ProductName: productName, Price: price, Category: category, __RequestVerificationToken: verificationtoken },
            function (product) {
               $('#productName').val('product.Name') 
            }, "json");

you can also make an ajax post like 

var myId = $('productId').val();
var data = "{ id : " + myId + " }";
$.ajax({
  type: "POST",
  url: @Url.Action("Edit", "PriceList"),
  data: data,
  success: function (e){
// e is the returned model or int or whatever you want to return
 },
  dataType: "json"
});

Leave a Reply