MVC 2 中视图和控制器之间传递值

发布于 2024-09-14 18:44:45 字数 787 浏览 1 评论 0原文

我经常对如何在 MVC 中的视图和控制器之间传递值感到困惑。我知道我可以在控制器中设置 ViewData 并在视图中使用它,但是反过来呢?

我发现我可以使用隐藏字段,然后通过 Request.Form["name"] 访问它,如下所示:

<% using (Html.BeginForm("Upload", "Customers", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {%>
<br />
<input id="currentDir" type="hidden" name="currentDir" value="" />
<input type="file" name="fileTextbox" id="fileTextbox" />
<br />
<br />
<input type="submit" value="Send" />
<% } %>

更复杂的是该值最初来自 jquery 脚本,所以这就是为什么输入字段是我能想到的唯一办法。但它仍然感觉不对......也许不是,但我基本上想知道是否有其他更“正确”的既定方法在视图和控制器之间传递值(两种方式)。应该使用查询字符串吗?如果是这样,它们在 html.beginform htmlhelper 中会是什么样子?

另外,我在这里尝试做的是为我的应用程序启用上传可能性。我正在尝试使整个应用程序尽可能“Ajaxy”。但这个表格将构成一个完整的帖子。有没有其他方法可以做到这一点,而不必重新加载整个页面来上传?

I'm constantly confused about how to pass values between Views and Controllers in MVC. I know I can set ViewData in the Controller and use that in the View, but what about the other way around?

What I have found is I can use a hidden field and then access it through Request.Form["name"] like this:

<% using (Html.BeginForm("Upload", "Customers", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {%>
<br />
<input id="currentDir" type="hidden" name="currentDir" value="" />
<input type="file" name="fileTextbox" id="fileTextbox" />
<br />
<br />
<input type="submit" value="Send" />
<% } %>

What complicates it even more is that the value originally comes from a jquery script, so that's why the input field was the only way I could think of. But it still feels wrong... Maybe it isn't but I'd basically like to know if there are other more "proper" established ways to pass values between the View and Controller (both ways). Should one use querystrings instead? If so, how would they look in the html.beginform htmlhelper?

Also, what I'm trying to do here is enable upload possibilities for my application. And I'm trying to make the whole application as "Ajaxy" as possible. But this form will make a complete post. Is there another way to do this and not have to reload the entire page for this upload?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

音栖息无 2024-09-21 18:44:45

让我们暂时忽略“AJAX-y”方面(因为这是一个不同的问题),只考虑在视图和控制器之间传递数据。我首先建议您查看 NerdDinner 教程,它提供了有关 MVC 如何使用的一些很好的见解工作原理以及如何使用 MVC 的一些功能。

为了解决数据如何从视图传递到控制器并返回的具体问题,有几种方法可以做到这一点。然而,对大多数人来说更有意义的是使用强类型视图的想法。

假设您有一个名为 Person 的模型。现在,不用担心我们如何存储 Person 数据 - 我们只是在 MVC 项目内的 Models 文件夹中有一个 Person 类。

public class Person {

  public string FirstName;
  public string LastName;

  public Person() {
    FirstName = "John";
    LastName = "Doe";
  }
}

当我们想要在视图中显示有关 Person 的数据时,我们会向特定控制器发出请求。在这种情况下(为了清楚起见),我们将此控制器称为 MainController。这将进入 Controllers 文件夹并被称为 MainController。让我们调用我们想要从 Index 获取数据的 Action(动作实际上只是一个专门的方法)。由于 ASP.NET MVC 路由的工作原理,我们服务器的路径将是: http://localhost/Main/Index。请注意控制器(减去“控制器”名称)和操作组成了路径。 (当然,第一部分是您的服务器名称。)

让我们看看您的控制器 - 现在我将使其保持非常简单:

public class MainController : Controller {

  public ActionResult Index() {
    Person person = new Person();
    return View(person);
  }
}

我们在 Index Action 中进行的操作是它返回一个 View(其中,默认情况下,与操作同名)以及与该视图相对应的模型。现在,我们必须创建我们的视图。

这里重要的部分是您想要对控制器中返回到视图的模型进行强类型化。您可以使用这一行(位于 aspx 文件中的第一行)来完成此操作。

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewUserControl<Project.Namespace.Person>" %>

请注意“Inherits”属性,并注意您的 Person 模型构成了该属性。

现在,只需像平常一样对视图的其余部分进行编码即可。假设我们要显示当前的人员名称,并允许某人更改名称。该页面看起来像这样(我并没有让它变得漂亮):

<% using (Html.BeginForm()) { %>
  <%: Html.LabelFor(model => model.FirstName) %>
  <%: Html.TextBoxFor(model => model.FirstName) %>
  <%: Html.LabelFor(model => model.LastName) %>
  <%: Html.TextBoxFor(model => model.LastName) %>

  <input type="submit" value="Submit" name="submitButton" />
<% } %>

这是在控制器和视图之间来回获取数据的重要部分。我们在这里所做的是,我们采用强类型视图(使用 Person 类进行类型化)并使用辅助方法(如 LabelFor 和 TextBoxFor)将模型与其数据结合在一起,并最终与操作结合在一起包含在控制器中(我们必须立即完成这里的开发)。

所以,您现在可以看到数据了。但是,如果用户更改名称并单击提交 - 我们希望页面显示新名称。这意味着我们需要向 MainController 添加一项操作 - 接收数据的操作。

[HttpPost]
public ActionResult Index(Person person) {
  // Do whatever you want with the Person model. Update a database, or whatever.
  return View(person);
}

这个动作看起来与我们刚刚开发的其他动作非常相似。然而,这个需要一个人对象(来自正在提交的表单),它使控制器有机会对该对象执行任何需要执行的操作。完成此操作后,您可以选择重定向到其他页面、重新显示页面(如果出现错误则很有用)或执行任意其他操作。

同样,NerdDinner 教程 中涵盖了所有内容(以及更多内容)。我强烈建议您阅读并遵循该内容。

至于您讨论的 AJAX-y 方面,前提仍然是相同的(尽管其中进行了一些 JavaScript/jQuery 工作)。我现在不会深入讨论,但 NerdDinner 教程 中也介绍了基础知识。

我希望这能让你开始。我记得当我第一次开始使用网络技术时也有点困惑,所以我希望这对你有所帮助!

Let's ignore the "AJAX-y" aspects for a moment (because that's a different issue) and just look at passing data between views and controllers. I would first recommend that you check out the NerdDinner Tutorial which provides some good insights into how MVC works and how you use some of the features of MVC.

To address your specific question of how data is passed from View to Controller and back, there are a few ways to do this. However, the one that tends to make sense to most people is the idea of using strongly-typed views.

Let's say you have a model called Person. For now, don't worry about how we store Person data - we just have a Person class in the Models folder inside your MVC project.

public class Person {

  public string FirstName;
  public string LastName;

  public Person() {
    FirstName = "John";
    LastName = "Doe";
  }
}

When we want to display data about Person in a View, we make a request to a specific controller. In this case (and for clarity) we'll call this controller the MainController. This will go in the Controllers folder and will be called MainController. Let's call the Action (an action is really just a specialized method) we want to get data from Index. Due to how ASP.NET MVC routing works, the path to our server will be: http://localhost/Main/Index. Notice the Controller (minus the "Controller" name), and the Action make up the path. (The first part is your server name, of course.)

Let's look at your controller - I'm going to keep it very simple for now:

public class MainController : Controller {

  public ActionResult Index() {
    Person person = new Person();
    return View(person);
  }
}

What we have going on inside the Index Action is that it is returning a View (which, by default, has the same name as the Action) and a model to correspond with that view. Now, we have to create our view.

The important part here is that you want to strongly-type the model that is being returned in the controller to your view. You do that with this line (which is first in your aspx file).

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewUserControl<Project.Namespace.Person>" %>

Notice the "Inherits" attribute and notice that your Person model makes up that attribute.

Now, just code the rest of your view as normal. Let's say we want to display the current Person name, and allow someone to change the name. The page would look like this (I'm not making this pretty):

<% using (Html.BeginForm()) { %>
  <%: Html.LabelFor(model => model.FirstName) %>
  <%: Html.TextBoxFor(model => model.FirstName) %>
  <%: Html.LabelFor(model => model.LastName) %>
  <%: Html.TextBoxFor(model => model.LastName) %>

  <input type="submit" value="Submit" name="submitButton" />
<% } %>

This is the important part about getting data back and forth between Controllers and Views. What we are doing here is that we are taking your strongly-typed view (which is typed with the Person class) and using helper methods (like LabelFor and TextBoxFor) to tie the model together with its data and, ultimately, together with the actions contained in the controller (which we have to finish developing here in one moment).

So, you can now see the data. But, if a user changes the name and clicks submit - we want the page to display the new name. This means we need to add one more action to MainController - the one that receives the data.

[HttpPost]
public ActionResult Index(Person person) {
  // Do whatever you want with the Person model. Update a database, or whatever.
  return View(person);
}

This action looks very similar to the other action we just developed. However, this one takes a person object (from the form that is being submitted) and it gives the controller an opportunity to do whatever needs to be done with that object. Once this is done, you can choose to redirect to a different page, redisplay the page (useful if there are errors), or do any number of other things.

Again, this is ALL covered (and much more) in the NerdDinner Tutorial. I highly recommend you read and follow through that.

As for the AJAX-y aspects you discussed, the premise is still the same (although there is a little bit of JavaScript/jQuery work that goes on in there). I won't go into it now, but the basics are also covered in the NerdDinner tutorial.

I hope this gets you started. I remember being a bit confused too when I first started working with web technologies, so I hope this helps you out!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文