【发布时间】:2020-11-29 18:15:23
【问题描述】:
我尝试搜索帖子,也没有任何结果,也许我没有使用正确的词。
我正在使用ASP.NET MVC 创建一个带有表单的网页。
表单有一个dropdownlist 和一个textbox。
dropdownlist 由数据库中的值填充。
textbox 将根据选定的dropdownlist 值填充来自同一个表和dropdownlist 的值。
我的目标是在我的视图中从我的controller 调用一个函数,这可能吗?
下面是我的代码
模型
namespace InsGE.Models
{
public class PersonModel
{
public List<SelectListItem> Fruits { get; set; } //DropDownList
public string Names { get; set; } //Textbox
}
}
控制器
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 sNames = person.Names;
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")
@Html.TextBoxFor(m => m.Names)
【问题讨论】:
标签: c# asp.net asp.net-mvc textbox dropdown