首页 > 解决方案 > asp.net MVC HTTPPost 返回视图

问题描述

在 HTTPPost 之后重定向到查看后出现以下错误。

The model item passed into the dictionary is of type '<>f__AnonymousType3`1[System.Int64]', but this dictionary requires a model item of type 'MVCProject.Models.AddEmployee'.

设想:

视图将使用 num 加载(如果通过)。我有另一种方法 HttpPost,它在返回视图上给出错误。请看下面的代码。

        public ActionResult AddEmployee(int? num)
        {
            AddEmployee e = new AddEmployee();

            //Business logic

            return View(e);
        }

        [HttpPost]
        public ActionResult AddEmployee(AddEmployee model)
        {
            //Add Employee logic
            return View("AddEmployee", new { num = model.EmpNum });
        }

标签: c#asp.net-mvc

解决方案


您正在返回视图而不是实际重定向。强烈推荐谷歌搜索并遵循 POST Redirect GET 模式。示例是:

[HttpPost]
public ActionResult AddEmployee(AddEmployee model)
{
   if (ModelState.IsValid)
   {
      //Add Employee logic
       var newEmployeeNumber = 1223; // Gotten from your add employee logic
       return RedirectToAction("AddEmployee", new { num = newEmployeeNumber });
   }
   return View(model);
}

推荐阅读