开发者

EntityFramework and MVC Views (Display)

I have a main table called Projects. This project has foreign keys on it named DeptId for department ID, SiteId for a Site ID. When the View gets displayed, I want to show the name of the department from the Department table and the name of the Site from the Site table, but when the data is saved back to the Project table, I want to save their IDs back to the Project table as the foreign key. So, I want to display the names from the Department table and from the Site table in the View but I want to save their related IDs to the Project table when the data in the View is saved back to the database. How should I go about doing this with EF? It is easy to deal with one table but I am not clear on how to render one field for display and save another field (ID) to the main project database. Thanks

----UPDATE------

I found an example of what I need to do but can you tell me how this dropdownlist gets populated. Does the first parameter in the dropdownlist match the ViewBag in the colt开发者_如何学运维roller?

--FROM VIEW--



            @Html.DropDownList("DepartmentID", String.Empty)
            @Html.ValidationMessageFor(model => model.DepartmentID)

--FROM CONTROLLER--



[HttpPost]
        public ActionResult Create(Course course)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    unitOfWork.CourseRepository.Insert(course);
                    unitOfWork.Save();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }
            PopulateDepartmentsDropDownList(course.DepartmentID);
            return View(course);

    private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
            {
                var departmentsQuery = unitOfWork.DepartmentRepository.Get(
                    orderBy: q => q.OrderBy(d => d.Name));
                ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment);
            }
            



This scenario is covered in this tutorial: http://www.asp.net/entity-framework/tutorials/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜