0

我正在工作(实际上是重构)一些项目,我有一个管理面板,有常规的管理操作 ADD / EDIT / LIST 他们所做的,是在数据库中插入/更新/或列出实体。

我在这个项目中发现,在 Add 和 Update ViewModels 和 Views 之间总是有重复的代码,它是复制粘贴,它们之间有微小的变化。是这样的:

EditCardsViewModel AddCardViewModel

正如我所说,几乎完全相同,然后 EditCardVIew 使用 EditCardsViewModel 作为 Model , AddView 使用 AddCardViewModel ,对我来说这是代码重复。当我联系创建这个的开发人员时,他说,这些是最佳实践,而且它非常易读,你知道在哪里可以找到所有东西......等等,我没有足够的经验来决定。所以问题是什么是最佳实践?我的意思是你能不能指点我一些好文章,解释如何在 MVC 中完成 ADD/UPDATE/LIST。

谢谢。

4

2 回答 2

1

是的,因为 Create 和 Edit 实际上是相同的,所以我通常会这样做:

控制器:

public class ActivityController : BaseController
    {
        public ActionResult Index()
        {
            var model = //Get your List model here...

            return View(model);
        }

        public ActionResult Create()
        {
            var model = new ActivityModel(); //Create new instance of whatever your model is
            return View("Edit", model); //NOTE: Pass the model to the "Edit view
        }

        public ActionResult Edit(int id)
        {
            var model = // your logic here to get your model based on ID param
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // your logic here to delete based on ID param
                return Json(new { Success = true, Message = "Entity updated" }); //AJAX result
            }
            catch (Exception x)
            {
                return Json(new { Success = false, Message = x.GetBaseException().Message }); //AJAX result
            }
        }

        [HttpPost]
        public ActionResult Update(ActivityModel model)//a single action to handle both add and edit operations
        {
            if (!ModelState.IsValid)
            {
                return Json(new { Success = false, Message = "Please correct any errors and try again" });//AJAX result
            }

            try
            {
                if (entity.Id == 0)
                {
                    //your logic for inserting
                }
                else
                {
                    //your logic for updating
                }

                return Json(new { Success = true });//AJAX result
            }
            catch (Exception x)
            {
                return Json(new { Success = false, Message = x.GetBaseException().Message }); //AJAX result
            }
        }
    }

这样,我最常需要创建 2 个视图:Index.cshtmlEdit.cshtml.

只需记住在您的编辑视图中有这个: @Html.HiddenFor(m => m.Id)

That will be used in the Update() action to check whether you need to do an insert or update.

Without seeing your code, I'm not sure if that applies to your situation though...

于 2013-03-10T10:56:25.230 回答
1

If you download MVCScaffolding the templates there are optimised for the AddEdit View type design. This Blog is a helpful resource for using it.

于 2013-03-11T08:42:01.283 回答