微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net MVC HTTPPost返回视图

如何解决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,它在返回View时给出错误。请参见下面的代码

        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 });
        }

解决方法

您正在返回视图,但实际上并未重定向。强烈建议使用Google搜索,并遵循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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。