我有一个ASP.NET MVC Razor
项目,我有DropDownList
来自Database
的数据,我尝试将所选值从DropDownList
插入Database
但我不能。
<div class="editor-label">
@Html.LabelFor(model => model.Parent_ID)
</div>
<div class="editor-field create-Bt3">
@Html.DropDownList("-Select Parent-", new SelectList(ViewBag.Parent, "Value", "Text"),"- Select Parent -")
</div>
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in data)
{
SelectListItem s = new SelectListItem();
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
if (Request.Files.Count > 0)
{
var uploadedFile = Request.Files[0];
var fileSavePath = "";
var fileName = "";
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
category.Path = "~/App_Data/Uploads/" + fileName;
}
category.Add_Date = DateTime.Now;
category.Last_Update = DateTime.Now;
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
答案 0 :(得分:0)
尝试使用onchange
的{{1}}事件。
DropDownList
现在在您的javascript中,使用@Html.DropDownList("-Select Parent-", new SelectList(ViewBag.Parent, "Value", "Text"),"- Select Parent -",new { @onchange="submitData(this);" } )
将该数据传递给您的控制器。
$.ajax
然后在你的控制器中添加一个参数。
<script type="text/javascript">
function submitData(e){
$.ajax({
type: 'POST',
dataType: 'json',
url: '@Url.Action("Create", "Home")',
data: ({ selectedValue: e.innerHTML }),
success: function (result) {
alert('success');
},
error: function (result) {
alert('error');
}
return false;
});
}
</script>
答案 1 :(得分:0)
而是使用此代码:
在您的视图中,绑定下拉列表如下:
@Html.DropDownListFor(model => model.User, new SelectList(Model.UserList, "Value", "Text"), new { @tabindex = "2" })
在模型中创建属性如下:
public string User{ get; set; }
public List<SelectListItem> UserList{ get; set; }
从数据库中获取数据以绑定您的下拉列表:
public List<SelectListItem> GetUserTypeList()
{
List<SelectListItem> listUsers = new List<SelectListItem>();
using (DbCommand command = DataAccess.CreateCommandTypeSPWithOutputCursor())
{
command.CommandText = "GetUserList";
command.CommandType = CommandType.StoredProcedure;
DataSet objDataSet = DataAccess.GetDataset(command);
foreach (DataRow row in objDataSet.Tables[0].Rows)
{
SelectListItem user = new SelectListItem();
user.Text = Convert.ToString(row["UserName"]).Trim();
user.Value = Convert.ToString(row["UserID"]).Trim();
listUsers.Add(user);
}
}
return listUsers;
}
在控制器动作方法中,将UserList分配给方法GetUserTypeList(),最后不要忘记将整个html放在form方法中,如下所示:
@using(Html.BeginForm("ActionName", "ControllerName", FormMethod.Post)) {
...
}
因此,您可以将下拉选择的值发布到数据库中。