ASP.NET MVC4,视图将旧值返回到控制器 [英] ASP.NET MVC4, View returning old values to controller

查看:90
本文介绍了ASP.NET MVC4,视图将旧值返回到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC和ASP.NET的新手.我的要求是,我必须在视图中第一次显示两个记录,并且视图包含一个"SWAP"按钮.当我按下此按钮时,应该执行控制器的后动作,它必须采用原始的viewmodel,并且需要交换两个记录,并且应该呈现相同的视图.每当我按交换"按钮时,此过程应继续进行.

I am new to MVC and ASP.NET. My requirement is, I have to display two records in my View for the firsttime and my ViewContains one 'SWAP' button. When I press this button, post action of the controller should execute and it has to take the original viewmodel and needs to swap the two records and should render the same view. This process should carryon whenever I press Swap button.

当我第一次单击SWAP时,它运行良好.但是当我下次单击时,我的后控制器操作将获取原始记录并显示相同的记录.

For the first time when I am clicking SWAP, it is working fine. But when I am clicking for next time, my post controller action is taking original records and displaying the same.

我的控制器代码,如下所示.

My Controller Code as shown Below.

public ActionResult Dedupe()
        {
            var selectedClients = TempData["SelectedClients"] as DedupeClientsViewModel;
            return this.View(selectedClients);
        }

        [HttpPost]
        public ActionResult Dedupe(DedupeClientsViewModel dedupeClients)
        {
            if (ModelState.IsValid)
            {
                //my functionality
            }
            return this.View(dedupeClients);
        }

是否需要对"ModelState"进行任何操作以从视图中获取新数据.

Is there anything that I need to do with "ModelState" to get the new data from the View.

推荐答案

由于您要从帖子中返回相同的模型,因此ASP.Net MVC假定您有要向用户展示的错误(因此,保留原始值).您可以通过清除整个模型的模型状态,或清除一个或多个字段的模型状态来解决此问题.见下文.当然,这将在您的控制器中完成.

Because you are returning the same model from a post, ASP.Net MVC is assuming that you have errors that you want to present back to the user (so it retains original values). You can fix this by either clearing the model state for the entire model, or clearing the model state for one or more fields. See below. This will be done, of course, in your controller.

ModelState.Clear(); //clear entire model state
ModelState.Remove("MyObject.MyProperty"); //clear only one property

Rick Strahl在他的博客上对此问题有很好的解释:

Rick Strahl has a good explanation of this issue on his blog: ASPNET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes

这篇关于ASP.NET MVC4,视图将旧值返回到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆