0

我有一个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");
    }
4

2 回答 2

0

尝试onchange使用DropDownList.

@Html.DropDownList("-Select Parent-", new SelectList(ViewBag.Parent, "Value", "Text"),"- Select Parent -",new { @onchange="submitData(this);" } )

现在在您的 javascript 中,将该数据传递$.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>

然后在您的控制器中添加一个参数。

[HttpPost]
public ActionResult Create(string selectedValue, Category category, IEnumerable<HttpPostedFileBase> files)
{
   //Do Database stuff to insert the selected value to DB
}
于 2013-01-10T06:12:24.053 回答
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)) {
...
}

因此,这就是您可以将下拉选择的值发布到数据库的方式。

于 2013-01-10T09:48:28.243 回答