Link to home
Start Free TrialLog in
Avatar of Arif Chowdhury
Arif ChowdhuryFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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
Avatar of Lokesh B R
Lokesh B R
Flag of India image

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

Avatar of Arif Chowdhury

ASKER

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
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

Its return values from database and it is in home controller as well. It is the common function to get data from database.
What is the return type of the method?

DataTable
List
DataSet
List
Can you show the code in GetData()?
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 );
        }
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

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

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

In which line you are getting this error?

can you debug ?
I cannot debug, it is giving the error directly
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
ASKER CERTIFIED SOLUTION
Avatar of Lokesh B R
Lokesh B R
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent solution, Many thanks
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
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
Hi Lokesh

Could you please give me a solution for the above error

Thanks
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

Hi Lokesh

After submitting, it is redirecting to the same page.

Thanks
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