C# 将数据从下拉列表保存到存储库

C# 将数据从下拉列表保存到存储库,c#,asp.net-mvc,C#,Asp.net Mvc,因此,我有一个Viewbag,它在我的CreateRazor视图中通过一个下拉列表,使用以下代码: 控制器 ViewBag.ActionTypes = new SelectList(query.AsEnumerable(), "ActionTypeID", "ActionTypeTitle"); 然后我的剃须刀会这样做 @Html.DropDownList("ActionTypeID", (IEnumerable<SelectListItem>)ViewBag.ActionT

因此,我有一个Viewbag,它在我的CreateRazor视图中通过一个下拉列表,使用以下代码:

控制器

 ViewBag.ActionTypes = new SelectList(query.AsEnumerable(), "ActionTypeID", "ActionTypeTitle");
然后我的剃须刀会这样做

  @Html.DropDownList("ActionTypeID", (IEnumerable<SelectListItem>)ViewBag.ActionTypes)
@Html.DropDownList(“ActionTypeID”,(IEnumerable)ViewBag.ActionTypes)
我被困在我的Post方法中应该放什么,以及如何从下拉列表中获取值


假设您有一个名为ActionType的模型,有人能给我指出正确的方向吗

public class ActionType
{
    public int ActionTypeID { get; set; }

    ...
}
由于您的SelectList使用相同的属性名称,ModelBinder将负责设置正确的发布值:

new SelectList(query.AsEnumerable(), "ActionTypeID", "ActionTypeTitle");
--------------------------------------------^
只需记住向您在操作中使用的模型类添加一个同名的属性:

-------------------------------v  Add the property to this class.
[HttpPost]
public ActionResult Create(SomeModel model)
{
}

这里有一个例子。假设实体框架已经生成了以下实体:

Person       Country
-------      -------
PersonID     CountryID
FullName     Name
CountryID


[HttpPost]
public ActionResult Create(PersonModel model)
{
    if (ModelState.IsValid)
    {
        DbEntities db = new DbEntities();
        Person person = new Person();
        person.FullName = model.FullName;
        person.CountryID = model.CountryID; // This value is from the DropDownList.

        db.AddToPersons(person);
        db.SaveChanges();

        return RedirectToAction("Index", "Home");       
    }

    // Something went wrong. Redisplay form.
    return View(model);
}

只需将发布的ID值设置为实体对象的外键属性

经典ASP从不支持C#或MVC框架。请更小心你的标签。对不起,我把ASP和它默认为ClassCI相信你的意思是“默认”。叛逃意味着其他事情。如何将返回值保存到我的数据库中,请使用example@StefanGowlar:这取决于后端使用的内容和项目的体系结构。你在使用存储库模式吗?是的,你能给我一个例子放在控制器中,我可以更改它吗?在我的存储库中,我有“void InsertActionType(ActionType ActionType);”然后在eRepository中,我有“public void InsertActionType(ActionType ActionType){context.ActionType.Add(ActionType);}”所以我应该能做到这一点?var viewbag=Action.ActionTypeID;ActionRepository.InsertActionType(viewbag);