c# - 使用 MySql 从 ASP.Net MVC 中的 ViewModel 填充(绑定)DropDownList
问题描述
我试图搜索帖子,也没有任何结果,也许我没有使用正确的词。
我需要一个解决方案,MVC
将DropDownList
使用Model class
和Html.DropDownListFor
Helper 方法从数据库中填充。
我在调试时没有错误Visual Studio 2019
,但它DropDownList
是空的。
请帮我。
我的代码如下
模型
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; }
}
}
控制器
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();
}
}
}
看法
@Html.DropDownListFor(m => m.Fruits, Model.Fruits, "Please select")
更新
现在调试Visual Studio 2019
返回错误
System.Web.Mvc.WebViewPage<TModel>.Model.get
Object reference not set to an instance of an object error
App_Web_sxdtrbqy
在视图中
@Html.DropDownListFor(m => m.Fruits, Model.Fruits, "Please select")
解决方案
您应该在 Index GET 方法中填充模型,然后将模型作为参数传递给 View。
[HttpGet]
public ActionResult Index()
{
PersonModel fruit = new PersonModel();
fruit.Fruits = PopulateFruits();
return View(fruit);
}
这是当您导航到索引页面时将调用的方法,因此您在此处放入模型的任何内容都会成为视图中的模型。
当您的用户按下某个按钮或表单标签内的链接以回发在视图中编辑的信息时,将调用 HttpPost 方法。
推荐阅读
- excel - 如果值不相等,如何将“For Next”重定向到另一个单元格并运行它?
- c - 使用 fgets 的函数返回 0
- audio - 嵌入式音频会议 API
- javascript - 无法使用 mySubscribers 参数检索超过 1000 个订阅者
- actionscript - 具有多个同名参数的函数如何工作?
- html - 通过单击 ReactJS 中的按钮下载文件
- python - 如何在 Python 和 tkinter 中找到这个 stringvar 问题的解决方案?
- node.js - “new Set”在nodejs中返回一个空集
- javascript - 如何在一个 monorepo 中使用多个 Dockerfile?
- php - 使用 jquery 序列化方法的多个表单不起作用