ASP.Net MVC C# Razor syntax

Arif Chowdhury
Arif Chowdhury used Ask the Experts™
on
Hello

I am new in MVC Razor and trying to convert a webform project to MVC. Now I am facing difficulties how to use dropdown which will be Razor C# syntax.

My Webfrom code -

aspx page - <asp:DropDownList runat="server" ID="ddl_1" AutoPostBack="true" >  </asp:DropDownList>
code behind -
if (ddl_1.Items.Count == 0)
            {
                ddl_1.DataSource = GetData(); //this function is working find and I am ok with this
                ddl_1.DataBind();

                ddl_1.Items.Insert(0, new ListItem("All", "0"));
                ddl_1.SelectedIndex = 0;                
            }

Please help me how it will be when I will use this in my MVC C# Razor project. I also want to show the selected value in a LABEL.

Thanks in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

In View

Home -> Index.cshtml

@Html.DropDownList("Role", null, "All", new { @class = "control-label" })
<span id="ddlValue"></span>


<script type="text/javascript">

  $("#Role").change(function () {
       
        $("#ddlValue").html($("#Role option:selected").text()); //Selected text

        //$("#ddlValue").html($("#Role").val()); // SelectedValue

    });

</script>

Open in new window



In Controller

HomeController -> Index

Get your data from the database and assign to ViewBag as following

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List<SelectListItem> roles = new List<SelectListItem>();

            roles.Add(new SelectListItem{ Value = "1", Text = "Admin" });
            roles.Add(new SelectListItem { Value = "2", Text = "Guest" });

            ViewBag.Role = new SelectList(roles, "Value", "Text");

            return View();
        }
}

Open in new window

Author

Commented:
Hi Lokesh

Many thanks for your solution and working. Also, I have a function called 'GetData();' which I need to use for to retrieve data. Do I need to use that function like this "roles.Add(new SelectListItem{ GetData(); });".

Many thanks
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

if the GetData() function return the DataTable, then you can use the following code.

List<SelectListItem> roles = new List<SelectListItem>();

            DataTable dt = GetData();

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    roles.Add(new SelectListItem { Value = dt.Rows[i]["Id"].ToString(), Text = dt.Rows[i]["Name"].ToString() });
                    //roles.Add(new SelectListItem { Value = "2", Text = "Guest" });
                }
            }

            ViewBag.Role = new SelectList(roles, "Value", "Text");

Open in new window

Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Author

Commented:
Its return values from database and it is in home controller as well. It is the common function to get data from database.
Lokesh B RDeveloper
Top Expert 2015

Commented:
What is the return type of the method?

DataTable
List
DataSet

Author

Commented:
List
Lokesh B RDeveloper
Top Expert 2015

Commented:
Can you show the code in GetData()?

Author

Commented:
private string[] GetData()
        {
            string[] bl = null;
            return bl = PrintRR.GetRP(ResList());
        }

private List<DataRow> ResList()
        {
            List<DataRow> rList = new List<DataRow>();
            string strBCl = SessionVariable("isBCl").ToString();
            string clN = SessionVariable("clN ").ToString();
         
            bool isBCl = strBCl .ToLower() == "true" ? true : false;

            return rList = PrintRR.GetRP(ACode, isBCl );
        }
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

Your GetData returning the string[].

try this code

List<SelectListItem> roles = new List<SelectListItem>();

            string[] items = GetData();

            if (items != null && items.Count() > 0)
            {
                for (int i = 0; i < items.ToList().Count; i++)
                {
                    roles.Add(new SelectListItem { Value = items[i].ToString(), Text = items[i].ToString() });
                }
            }
ViewBag.Role = new SelectList(roles, "Value", "Text");

Open in new window

Author

Commented:
Hi Lokesh

Now I am getting 'Object reference not set to an instance of an object'. Do you think it is related something in our database setup.

Also, can you please show me how I will passed the dropdown selected value in a variable into the controller.

Many thanks
Lokesh B RDeveloper
Top Expert 2015

Commented:
You need to use strongly typed model.

Check this tutorial for ways to bind dropdownlist and assign the value

Author

Commented:
Many thanks Lokesh

Author

Commented:
Hi Lokesh

I am trying but still getting the same error 'Object reference not set to an instance of an object.', Could you please help me.

Thanks
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

In which line you are getting this error?

can you debug ?

Author

Commented:
I cannot debug, it is giving the error directly

Author

Commented:
Hi Lokesh

I find out the problem and it was in the database.

I have another request, could you please help me how to store the selected dropdown value in a variable inside the controller.

Many thanks
Developer
Top Expert 2015
Commented:
Hi,

You can add a HiddenField in the View and when submit assign the DropDownList selected value to that and get the value in controller.

Controller

 
[HttpPost]
        public ActionResult Insert()
        {
            if (Request.Form["ddl"] != null)
            {
                string value = Request.Form["ddl"].ToString();
            }
            return View();
        }

Open in new window


View

@using (Html.BeginForm("Insert", "Home", FormMethod.Post))
{
    @Html.DropDownList("Role", null, "All", new { @class = "control-label" })
    <span id="ddlValue"></span>

    @Html.Hidden("ddl")
    <input type="submit" value="Submit" id="btnSubmit" />
}

<script type="text/javascript">

    $("#btnSubmit").click(function () {

        $("#ddl").val($("#Role option:selected").text());

    });

</script>

Open in new window

Author

Commented:
Excellent solution, Many thanks

Author

Commented:
Hi Lokesh

Now I am trying to do that and getting below error, any idea -

"The ViewData item that has the key 'Ddl1' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

@Html.DropDownList("Ddl1", null, new { @class = "control-label" })".

Please help me if you know how to do this. Also, ignore my message I sent you before.

Thanks in advance

Thanks

Author

Commented:
Hi Lokesh

Still I am getting the same error, this is happening as soon as I am selecting the a value from dropdown list and click the submit button -

"There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Ddl1'"

@Html.DropDownList("Ddl1", null, "All", new { @class = "control-label" })"

Could you please help me about this problem.

Many thanks

Author

Commented:
Hi Lokesh

Could you please give me a solution for the above error

Thanks
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

After submitting for which page it is redirecting to?

same page means you need to send the DropDownList values in submit click as well.

[HttpPost]
        public ActionResult Insert()
        {
            if (Request.Form["ddl"] != null)
            {
                string value = Request.Form["ddl"].ToString();
            }

ViewBag.Role = new SelectList(roles, "Value", "Text"); // Get the data from the database to dropdownlist
            return View();
        }

Open in new window

Author

Commented:
Hi Lokesh

After submitting, it is redirecting to the same page.

Thanks
Lokesh B RDeveloper
Top Expert 2015

Commented:
Hi,

Then you need to write the same code to get the Dropdownlist in the Insert() as well.

[HttpPost]
        public ActionResult Insert()
        {
            if (Request.Form["ddl"] != null)
            {
                string value = Request.Form["ddl"].ToString();
            }

ViewBag.Ddl1= new SelectList(roles, "Value", "Text"); // Get the data from the database to dropdownlist
            return View();
        }

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial