I tried to search posts, without any result either, maybe I didn't use the right words.
I need a solution in MVC for DropDownList will be populated from database using Model class and the Html.DropDownListFor Helper method.
I don't have error on Visual Studio 2019 debug, but the DropDownList is empty.
Please, help me.
My code below
Model
namespace InsGE.Models
{
public class PersonModel
{
public List<SelectListItem> Fruits { get; set; }
public string Namex { get; set; }
public string Codex { get; set; }
[Required]
[Display(Name = "CL")]
public string CL { get; set; }
[Required]
[Display(Name = "Ticket")]
public string Ticket { get; set; }
}
}
Controller
namespace InGE.Controllers
{
public class HomeController : Controller
{
private static List<SelectListItem> PopulateFruits()
{
string sql;
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
sql = @String.Format("SELECT * FROM `dotable`; ");
using (MySqlCommand cmd = new MySqlCommand(sql))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["sName"].ToString(),
Value = sdr["sCode"].ToString()
});
}
}
con.Close();
}
}
return items;
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
string sCl = person.CL;
string sTicket = person.Ticket;
string sName = person.Namex;
string sCode = person.Codex;
PersonModel fruit = new PersonModel();
fruit.Fruits = PopulateFruits();
return View();
}
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
View
@Html.DropDownListFor(m => m.Fruits, Model.Fruits, "Please select")
Update
Now the debug of Visual Studio 2019 return error
System.Web.Mvc.WebViewPage<TModel>.Model.get
Object reference not set to an instance of an object error
App_Web_sxdtrbqy
in the view
@Html.DropDownListFor(m => m.Fruits, Model.Fruits, "Please select")