Controller
public class ProController : Controller { string CS = ConfigurationManager.ConnectionStrings["OnlineInventoryDB"].ConnectionString;
[HttpGet]
public ActionResult Create()
{
Get_catagory();
return View();
}
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post(Product product)
{
if (ModelState.IsValid)
{
pro.AddProduct(product);
return RedirectToAction("Index");
}
return View();
}
public void Get_catagory()
{
SqlConnection con = new SqlConnection(CS);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter sda = new SqlDataAdapter("DDLCatagory", con);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
sda.Fill(dt);
List<SelectListItem> ddlcatlist = new List<SelectListItem>();
foreach(DataRow dr in dt.Rows)
{
ddlcatlist.Add(new SelectListItem { Text = dr["Catagory"].ToString(), Value = dr["Cat_ID"].ToString() });
}
ViewData["cataglistddl"] = ddlcatlist;
}
}
强烈打字
@model BuisnessLogics.Product
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Prod_Catagory, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ddlcataglist", ViewData["cataglistddl"] as List<SelectListItem>,"Select Cataegory", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Prod_Catagory, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
在页面提交时,没有显示“IEnumerable”类型的ViewData项,其中显示了“ddlcataglist”键,并且未提交页面。
答案 0 :(得分:0)
您还需要在post方法中重新绑定您的下拉列表。
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post(Product product)
{
Get_catagory();
if (ModelState.IsValid)
{
pro.AddProduct(product);
return RedirectToAction("Index");
}
return View();
}