ASP.Net MVC和状态 - 如何保持请求之间的状态 [英] ASP.Net MVC and state - how to keep state between requests

查看:241
本文介绍了ASP.Net MVC和状态 - 如何保持请求之间的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个相当有经验ASP.Net开发者最近刚刚使用MVC开始,我发现自己挣扎了一下,以我的心态从一个做事的传统的服务器控件和事件处理的方式发生变化,事物的更具活力的MVC方式。我想我慢慢变有,但有时MVC神奇抛出了我。

As a fairly experienced ASP.Net developer just recently starting using MVC, I find myself struggling a bit to change my mindset from a traditional "server control and event handler" way of doing things, into the more dynamic MVC way of things. I think I am slowly getting there, but sometimes the MVC "magic" throws me off.

我目前的方案是创建一个网页,允许用户浏览本地文件,把它上传到服务器,并重复这一点,直到他有一个文件列表的工作。当他是高兴的文件列表(将被显示在页面上的网格),他将点击按钮处理的文件,并提取将被存储在数据库中的一些数据。

My current scenario is to create a web page that allows the user to browse a local file, upload it to the server and repeat this until he has a list of files to work with. When he is happy with the file list (which will be displayed in a grid on the page), he will click a button to process the files and extract some data that will be stored in a database.

最后一部分是不是那么重要,现在我用的微不足道建立文件列表,并坚持要求之间的名单东西挣扎。在传统的方法,这将是非常简单 - 数据将在ViewState中被持久化。但在MVC我需要通过控制器和视图之间的数据,我不完全得到这个是如何工作的。

The last part is not so important, right now I am struggling with something as trivial as building up a list of files, and persisting that list between requests. In the traditional approach this would be extremely simple - the data would be persisted in ViewState. But in MVC I need to pass the data between the controller and the views, and I don't fully get how this is supposed to work.

我想我最好张贴我的编码这个问题的解释相当不完整的企图。

I guess I better post my rather incomplete attempt of coding this to explain the problem.

为了保持我的文件列表中的数据,我创建了一个视图模型,基本上是文件的类型列表中,有一些额外的元数据:

In order to keep my file list data, I have created a viewmodel that is basically a typed list of files, along with some extra metadata:

public class ImportDataViewModel
{
    public ImportDataViewModel()
    {
        Files = new List<ImportDataFile>();
    }

    public List<ImportDataFile> Files { get; set; }
...

在看,我有浏览和上传文件的表单:

In the view, I have a form for browsing and uploading the file:

<form action="AddImportFile" method="post" enctype="multipart/form-data">
  <label for="file">
    Filename:</label>
  <input type="file" name="file" id="file" />
  <input type="submit" />
  </form>

该视图使用视图模型作为其模型:

The view is using the viewmodel as its model:

@model MHP.ViewModels.ImportDataViewModel

这将文件发送到我的行动:

This will send the file to my action:

public ActionResult AddImportFile(HttpPostedFileBase file, ImportDataViewModel importData)
    {

        if (file.ContentLength > 0)
        {
            ImportDataFile idFile = new ImportDataFile { File = file };
            importData.Files.Add(idFile);
        }

        return View("DataImport", importData);
    }

此操作将返回包含文件的列表视图模型实例一起为DataImport页面视图。

This action returns the view for the DataImport page along with the viewmodel instance containing the list of files.

这很好地工作到某一点,我可以浏览一个文件并上传它,我可以看到的动作里面的视图模型数据,然后又如果我把一个断点的观点和调试this.Model内幕,一切都很好。

This works nicely up to a certain point, I can browse a file and upload it, and I can see the viewmodel data inside the action, and then also if I put a breakpoint inside the view and debug "this.Model", everything is fine.

不过,如果我尝试上传另一个文件,把AddImportFile行动中的断点时,IMPORTDATA参数为空。所以观点显然是不及格的模型的当前实例的动作。

But then, if I try to upload another file, when putting a breakpoint inside the AddImportFile action, the importData parameter is empty. So the view is obviously not passing the current instance of its model to the action.

在MVC样我已经通过,模型实例是神奇传递到操作方法作为参数,所以为什么是空的了?

In the MVC samples I have been through, the model instance is "magically" passed to the action method as a parameter, so why is it empty now?

我认为真正的问题是我的MVC的了解有限,这有可能是一个非常简单的解决这个。不管怎么说,我将非常感激,如果有人能在正确的方向指向我。

I assume the real problem is my limited understanding of MVC, and that there is probably a very simple solution to this. Anyways, I would be extremely grateful if somebody could point me in the right direction.

推荐答案

它已经因为我张贴的问题,这是很我的MVC的一点经验和知识,有色一段时间。尽管如此,我收到了一些非常有用的投入,最终导致我找到一个解决方案,也收获了MVC的一些见解。

It's been some time since I posted the question, which was quite colored by my little experience and knowledge of MVC. Still I received some quite useful input, that eventually led me to find a solution and also gain some insight of MVC.

什么摆在首位扔我了,是你可以有一个强类型的对象作为参数的控制,如:

What threw me off in the first place, was that you could have a controller with a strongly typed object as a parameter, like this:

public ActionResult DoSomething(MyClass myObject)...

该对象源于同一个控制器:

This object originated from the same controller:

...
return View(myObject);
...

这使我相信,对象居住在这些两步,那我不知可以指望,你可以将它发送到视图,做一些事情,然后神奇又拿回来给控制器。

This lead me to believe that the object lived throughout these two steps, and that I somehow could expect that you could send it to the view, do something and then "magically" get it back to the controller again.

阅读了有关模型绑定之后,我明白,这当然并非如此。的看法是完全死了,静态的,除非你的地方存储信息,就消失了。

After reading up about model binding, I understood that this is of course not the case. The view is completely dead and static, and unless you store the information somewhere, it is gone.

回过头来看看这个问题,这是选择和从客户端上传文件,并建立这些文件的列表中显示出来,我意识到,一般有存储请求之间的信息MVC方式有三种:

Going back to the problem, which was selecting and uploading files from the client, and building up a list of these files to be displayed, I realized that in general there are three ways to store information between requests in MVC:


  1. 您可以存储在视图中表单字段的信息,并张贴回控制器后

  2. 您可以在某些类型的存储坚持它,例如一个文件或数据库

  3. 您可以在服务器内存acessing一种生活在整个请求的对象存储,例如会话变量

在我的情况,我有两种基本类型的信息坚持:
  1.文件元数据(文件名,文件大小等)
  2.文件内容

In my case, I had basically two types of information to persist: 1. The file metadata (file name, file size etc.) 2. The file content

的由这本书的方法很可能是储存在表单字段中的元数据,并在一个文件中或以db文件内容。但也有另一种方式。因为我知道我的文件非常小,会出现只有几个人,而这个解决方案将永远不会在服务器场或类似的部署,我想探索会话变量的#3选项。该文件也没有兴趣坚持超越会话 - 它们被处理和丢弃的,所以我不想将它们存储在我的分贝。

The "by-the-book" approach would probably be to store the metadata in form fields, and the file contents in a file or in db. But there is also another way. Since I know my files are quite small and there will be only a few of them, and this solution will never be deployed in a server farm or similar, I wanted to explore the #3 option of session variables. The files are also not interesting to persist beyond the session - they are processed and discarded, so I did not want to store them in my db.

阅读这篇优秀的文章后:
<一href=\"http://www.$c$cproject.com/Articles/191422/Accessing-ASP-NET-Session-Data-Using-Dynamics\">Accessing ASP.NET会话数据使用动态

After reading this excellent article: Accessing ASP.NET Session Data Using Dynamics

我确信。我只是创造了一个sessionbag类的文章中描述,然后我可以做在我的控制器以下内容:

I was convinced. I simply created a sessionbag class as described in the article, and then I could do the following in my controller:

    [HttpPost]
    public ActionResult AddImportFile(HttpPostedFileBase file)
    {

        ImportDataViewModel importData = SessionBag.Current.ImportData;
        if (importData == null) importData = new ImportDataViewModel();

        if (file == null)
            return RedirectToAction("DataImport");

        if (file.ContentLength > 0)
        {
            ImportDataFile idFile = new ImportDataFile { File = file };
            importData.Files.Add(idFile);
        }

        SessionBag.Current.ImportData = importData;

        return RedirectToAction("DataImport");
    }

我充分认识到,在大多数情况下,这将是一个坏的解决方案。但对于服务器内存的几KB的文件占用,并与这一切简单,我觉得它的工作也很完美我。

I am fully aware that in most cases, this would be a bad solution. But for the few kb of server memory the files occupy and with the simplicity of it all, I think it worked out very nicely for me.

使用SessionBag的额外的奖金是,如果用户输入不同的菜单项,然后回来的时候,文件列表仍然会在那里。这不会是这种情况例如选择表单域/文件存储选项时。

The additional bonus of using the SessionBag is that if the user entered a different menu item and then came back, the list of files would still be there. This would not be the case e.g. when choosing the form fields/file storage option.

作为最后的一句话,我意识到SessionBag是很容易被滥用,因为使用的简单性。但是,如果你使用它这是什么意思了,即会话数据,我认为这可能是一个强大的工具。

As a final remark, I realize that the SessionBag is very easy to abuse, given the simplicity of use. But if you use it for what it is meant for, namely session data, I think it can be a powerful tool.

这篇关于ASP.Net MVC和状态 - 如何保持请求之间的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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