簡體   English   中英

如何將數據從數據庫傳遞到控制器,然后在選擇選項標簽中顯示在視圖中。 ASP.NET MVC5

[英]How to pass data from database to controller and then show in view in select option tag. ASP.NET MVC5

我正在嘗試從我能夠執行的數據庫中獲取數據,但我似乎無法將其傳遞給 html 中視圖的選擇選項標簽。

我試過使用字符串並傳遞它,但它只是傳遞第一個值。 也無法通過字符串數組傳遞它

public ActionResult GetDetails()
{
    SqlConnection con;
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    con = new SqlConnection(constr);
    con.Open();
    string sqlCommand = "SELECT *FROM cityname";
    SqlCommand cmd = new SqlCommand(sqlCommand, con);
    SqlDataReader read;

    read = cmd.ExecuteReader();

    List<string> str = new List<string>();

    while(read.Read())
    {
        str.Add(read.GetValue(1).ToString());
    }

    ViewBag.mydata = str;

    return View();
}

我希望能夠在此展示它

<select class="mdb-select md-form" id="PersonCity" name="PersonCountry" onchange="run1();">
    <option value="" disabled selected>Choose your Country</option>
    <option value='$country_name'>$country_name</option>

嘗試為此替換您的 html

@Html.DropDownList("value", new SelectList(ViewBag.mydata))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM