English 中文(简体)
如何将模型推向具有其他参数的行动
原标题:How to pass model to an action which have other parameters

我在以下问题上的问题是,我如何向“Employee”行动发出《示范国家错误》,当时我通过删除“Employee”中的捕获部分。

   public ActionResult Employee(int ID, string Name)
    {
        EmployeeListModel model = new EmployeeListModel (ID, projectName);
        return View(model);
    }

 public ActionResult DeleteEmployee(Employee emp)
    {

        try
        {
            emp.Delete();
            return RedirectToAction("Employee", new { ID = emp.ID, Name = emp.Name });
        }

        catch (Exception e)
        {
            EmployeeListModel model = new EmployeeListModel (emp.ID, emp.Name);
            ModelState.AddModelError("Error", e.Message);
            return RedirectToAction("Employee", model);
        }
    }

“Employee”模式;我仍然无法将身份证和姓名作为参数。

问题回答

使用<代码>TempData,在多种控制器行动中坚持<代码>ModelState。

MvcContrib有一个行动过滤器。 杰里米·Skinner在。 来文方的链接被打破,因此我将守则张贴如下。

ModelStateToTempDataAttribute Source Code

/// <summary>
/// When a RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData.
/// When a ViewResultBase is returned from an action, any ModelState entries that were previously copied to TempData will be copied back to the ModelState dictionary.
/// </summary>
public class ModelStateToTempDataAttribute : ActionFilterAttribute
{
    public const string TempDataKey = "__MvcContrib_ValidationFailures__";

    /// <summary>
    /// When a RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData.
    /// When a ViewResultBase is returned from an action, any ModelState entries that were previously copied to TempData will be copied back to the ModelState dictionary.
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var modelState = filterContext.Controller.ViewData.ModelState;

        var controller = filterContext.Controller;

        if(filterContext.Result is ViewResultBase)
        {
            //If there are failures in tempdata, copy them to the modelstate
            CopyTempDataToModelState(controller.ViewData.ModelState, controller.TempData);
            return;
        }

        //If we re redirecting and there are errors, put them in tempdata instead (so they can later be copied back to modelstate)
        if((filterContext.Result is RedirectToRouteResult || filterContext.Result is RedirectResult) && !modelState.IsValid)
        {
            CopyModelStateToTempData(controller.ViewData.ModelState, controller.TempData);
        }
    }

    private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
    {
        if(!tempData.ContainsKey(TempDataKey)) return;

        var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
        if(fromTempData == null) return;

        foreach(var pair in fromTempData)
        {
            if (modelState.ContainsKey(pair.Key))
            {
                modelState[pair.Key].Value = pair.Value.Value;

                foreach(var error in pair.Value.Errors)
                {
                    modelState[pair.Key].Errors.Add(error);
                }
            }
            else
            {
                modelState.Add(pair.Key, pair.Value);
            }
        }
    }

    private static void CopyModelStateToTempData(ModelStateDictionary modelState, TempDataDictionary tempData)
    {
        tempData[TempDataKey] = modelState;
    }
}

Here are some similar posts

从这种观点看,示范国家词典是“观点”的一部分,因此试图通过浏览数据,至少在MVC 3(这种方式也采用旧版本)。 你们不需要通过这一模式,而是以这种方式加以利用。

However, i don t know if model state errors are retained if you do a redirect; you may want to return the response directly instead:

return View("Employee", model);

HTH.

身份识别和姓名的数值正在由你通过“意见”的“行动结果”中总结:

  • Model.ID
  • Model.Name

请注意,@Brian是正确的,因为你需要使用“意见”而不是“反应行动”行动,否则就会丢失模范错误。 另一种做法是把你的模式储存在TmData,这实际上是在届会目标周围的一个特殊总结。 如果你需要确保适当更新你的遗体,那么你就有必要使用像“再行动”这样的东西。

将示范国家储存在TmData:

TempData["ModelState"] = ModelState;

Then merge the ModelState using an action filter for example:

protected override void OnActionExecuted(ActionExecutedContext context)
{
    filterContext.Controller.ViewData.ModelState.Merge((ModelStateDictionary)TempData["ModelState"]);
}

希望这一帮助。

Try below code //as a best practise always use Viewmodel e.g. employeeViewMode and strongly type your view to viewmodel public class EmployeviewModel { public int id; public string name; public string errormessage; } public ActionResult Employee(int ID) { EmployeeListModel model = new EmployeeListModel(ID, projectName); EmployeviewModel vm = new EmployeviewModel(); vm.id = model.id; vm.name = model.name; if (TempData.Keys.Count() > 0) { vm.errormessage = TempData["errormessage"]; } return View(vm); }

    public ActionResult DeleteEmployee(Employee emp)
    {
        try
        {
            emp.Delete();
            return RedirectToAction("Employee", new { ID = emp.ID, Name = emp.Name });
        }

        catch (Exception e)
        {
            //use TempData to store error message
            TempData["ErrorMessage"] = e.message;
            return RedirectToAction("Employee", emp.ID);
        }
    }




相关问题
WebForms and ASP.NET MVC co-existence

I am trying to make a WebForms project and ASP.NET MVC per this question. One of the things I ve done to make that happen is that I added a namespaces node to the WebForms web.config: <pages ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

Create an incremental placeholder in NHaml

What I want to reach is a way to add a script and style placeholder in my master. They will include my initial site.css and jquery.js files. Each haml page or partial can then add their own required ...

asp.net mvc automapper parsing

let s say we have something like this public class Person { public string Name {get; set;} public Country Country {get; set;} } public class PersonViewModel { public Person Person {get; ...

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor)...

ASP.NET MVC: How should it work with subversion?

So, I have an asp.net mvc app that is being worked on by multiple developers in differing capacities. This is our first time working on a mvc app and my first time working with .NET. Our app does not ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

热门标签