ASP.Net MVC C# Razor syntax

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
Arif ChowdhuryAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lokesh B RDeveloperCommented:
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

Arif ChowdhuryAuthor 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 RDeveloperCommented:
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

OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Arif ChowdhuryAuthor 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 RDeveloperCommented:
What is the return type of the method?

DataTable
List
DataSet
Arif ChowdhuryAuthor Commented:
List
Lokesh B RDeveloperCommented:
Can you show the code in GetData()?
Arif ChowdhuryAuthor 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 RDeveloperCommented:
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

Arif ChowdhuryAuthor 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 RDeveloperCommented:
You need to use strongly typed model.

Check this tutorial for ways to bind dropdownlist and assign the value
Arif ChowdhuryAuthor Commented:
Many thanks Lokesh
Arif ChowdhuryAuthor 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 RDeveloperCommented:
Hi,

In which line you are getting this error?

can you debug ?
Arif ChowdhuryAuthor Commented:
I cannot debug, it is giving the error directly
Arif ChowdhuryAuthor 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
Lokesh B RDeveloperCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Arif ChowdhuryAuthor Commented:
Excellent solution, Many thanks
Arif ChowdhuryAuthor 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
Arif ChowdhuryAuthor 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
Arif ChowdhuryAuthor Commented:
Hi Lokesh

Could you please give me a solution for the above error

Thanks
Lokesh B RDeveloperCommented:
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

Arif ChowdhuryAuthor Commented:
Hi Lokesh

After submitting, it is redirecting to the same page.

Thanks
Lokesh B RDeveloperCommented:
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.