0

使用 mvc3,是否有一些变量可以告知我是否来自 Create to Edit 操作?

如果在 GET 中也使用路由,我想要某种行为,否则如果 CreateAction 已被触发,我想打开不同的上下文编辑。

第一个解决方案失败:创建额外的操作编辑,触发:The current request for action 'Edit' on controller type 'XController' is ambiguous between the two action methods

更重要的是,是否存在对 MVC 的误解?这个解决方案对任何人来说听起来很奇怪吗?我对 mvc 有很大的疑问。:)

4

4 回答 4

1

您可以向您的编辑操作添加一个可选参数,以标记您是否来自添加操作,或者您可以创建一个全新的操作(使用来自编辑的唯一名称)。

前者看起来像:

public ActionResult Edit(int id, bool? fromCreate = false)
{
    if(fromCreate)
    {
        // do your special processing
    }
}

显然,后者将是:

public ActionResult Edit(int id)
{
}

public ActionResult EditNewlyCreated(int id)
{
}
于 2012-04-23T18:33:25.227 回答
0

In your create view or create controller action (no razor markup if its in the action):

@{ TempData["FromCreate"] = true; }

And then in your edit get action:

public ActionResult Edit()
{
 if( TempData.ContainsKey("FromCreate") )
 {
  var fromCreate = (bool)TempData["FromCreate"];
  TempData.Remove("FromCreate");
  if( fromCreate )
  {
   //insert logic
  }
 }
}
于 2012-04-23T19:05:11.420 回答
0

If you have something linke this in MyView view:

          @model ModelClass

          @Html.BeginForm()
          {
               if(Model.Id > 0)
               {
                   @Html.HiddenFor(m => m.Id);
               }

               ...
          }

And in controller:

     public ActionResult Edit(int id)
     {
           var model = modelRepository.GetById(id);
           Return View("MyView", model);
     }

     [HttpPost]
     public ActionResult Edit(int id, FormCollection collection)
     {
           var model = modelRepository.GetById(id);
           TryUpdateModel(model)
           {
                modelRepository.Save(model);
           }
     }

     public ActionResult Create()
     {
           var model = new ModelClass();
           Return View("MyView", model);
     }

     [HttpPost]
     public ActionResult Create(ModelClass model)
     {
           ...
     }

In view, if Model.Id > 0 it means that we entered view using Edit action and when form posts, if there will be Id field in post parameters (hidden for id) then Edit(with HttpPost) will be called, else if there will not be Id parameter then Create action will be called

于 2012-04-23T19:52:41.070 回答
-1

If you have 2 Edit methods, they must have different method inputs to differentiate them.

public ActionResult Edit(int id)
{
    return View(db.GetWidget(id));
}

public ActionResult Edit(int id, string username)
{
    ViewBag.Username = username;
    return View(db.GetWidget(id));
}

Or, just make the method into one with an optional parameter

public ActionResult Edit(int id, string username = "")
{
    ViewBag.Username = username;
    return View(db.GetWidget(id));
}

I would also recommend painting a method attribute such as [HttpGet], [HttpPost], etc.

于 2012-04-23T18:36:05.393 回答