C# MVC Razor 隐藏输入和传递值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11325616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:26:08  来源:igfitidea点击:

MVC Razor Hidden input and passing values

c#htmlasp.net-mvcasp.net-mvc-3model-view-controller

提问by Francis Rodgers

I am pretty sure I am doing something wrong here. Over the last 2 months we have been developing a web app using MVC and Razor and we never thought of using the form element. Now so much has already been done with master pages and sub pages that it means restructuring most of our code in order to use form element and the would result in multiple form elements on a page.

我很确定我在这里做错了什么。在过去的 2 个月里,我们一直在使用 MVC 和 Razor 开发 Web 应用程序,但我们从未想过要使用表单元素。现在母版页和子页已经做了很多工作,这意味着重构我们的大部分代码以使用表单元素,这将导致页面上有多个表单元素。

That aside, in Asp.Net if I wanted to access any control in the C# code behind I could just give it an ID="SomeID" and a RUNAT="SERVER". Then in my code behind I could set its value and properties.

除此之外,在 Asp.Net 中,如果我想访问背后的 C# 代码中的任何控件,我可以给它一个 ID="SomeID" 和一个 RUNAT="SERVER"。然后在我后面的代码中,我可以设置它的值和属性。

When I do this in Razor, we use lines like:

当我在 Razor 中执行此操作时,我们使用以下行:

 <input id="hiddenPostBack" runat="server" type="hidden" />

Why can't I access this in the controller? I want to detect a postback and set the value to false if it is the first time the page loads, and if not, then set the value to true. Then based on this, I will read it either server side or client side and do something.

为什么我不能在控制器中访问它?如果是第一次加载页面,我想检测回发并将值设置为 false,如果不是,则将值设置为 true。然后基于此,我将在服务器端或客户端读取它并做一些事情。

My real question is, how do I "do something" both server side and client side given that I don't have a form element. I was under the impression that if I wanted to pass values from client to server and back, the easiest way to do this is with a hidden input. But I am just not getting how to accomplish this with MVC3 and razor.

我真正的问题是,鉴于我没有表单元素,我如何在服务器端和客户端“做某事”。我的印象是,如果我想将值从客户端传递到服务器并返回,最简单的方法是使用隐藏输入。但我只是不知道如何使用 MVC3 和剃刀来实现这一点。

Thanks in advance for your help.

在此先感谢您的帮助。

采纳答案by Steve Owen

A move from WebForms to MVC requires a complete sea-change in logic and brain processes. You're no longer interacting with the 'form' both server-side and client-side (and in fact even with WebForms you weren't interacting client-side). You've probably just mixed up a bit of thinking there, in that with WebForms and RUNAT="SERVER"you were merely interacting with the buildingof the Web page.

从 WebForms 到 MVC 的转变需要逻辑和大脑过程的彻底改变。您不再与服务器端和客户端的“表单”交互(事实上,即使使用 WebForms,您也没有与客户端交互)。您可能只是在那里混淆了一些想法,在 WebForms 中,RUNAT="SERVER"您只是在与 Web 页面的构建进行交互。

MVC is somewhat similar in that you have server-side code in constructing the model (the data you need to build what your user will see), but once you have built the HTML you need to appreciate that the link between the server and the user no longer exists. They have a page of HTML, that's it.

MVC 有点相似,因为您在构建模型时拥有服务器端代码(构建用户将看到的数据所需的数据),但是一旦构建了 HTML,您就需要了解服务器和用户之间的链接不复存在。他们有一个 HTML 页面,就是这样。

So the HTML you are building is read-only. You pass the model through to the Razor page, which will build HTML appropriate to that model.

因此,您正在构建的 HTML 是只读的。您将模型传递到 Razor 页面,该页面将构建适合该模型的 HTML。

If you want to have a hidden element which sets true or false depending on whether this is the first view or not you need a bool in your model, and set it to True in the Action if it's in response to a follow up. This could be done by having different actions depending on whether the request is [HttpGet] or [HttpPost] (if that's appropriate for how you set up your form: a GET request for the first visit and a POST request if submitting a form).

如果你想要一个隐藏元素,它根据是否是第一个视图来设置 true 或 false,你需要在模型中使用 bool,如果它是对后续操作的响应,则在 Action 中将其设置为 True。这可以通过根据请求是 [HttpGet] 还是 [HttpPost] 执行不同的操作来完成(如果这适合您设置表单的方式:第一次访问的 GET 请求和提交表单的 POST 请求)。

Alternatively the model could be set to True when it's created (which will be the first time you visit the page), but afteryou check the value as being True or False (since a bool defaults to False when it's instantiated). Then using:

或者,模型可以在创建时设置为 True(这将是您第一次访问该页面),但是您检查该值是 True 还是 False 之后(因为 bool 在实例化时默认为 False)。然后使用:

@Html.HiddenFor(x => x.HiddenPostBack)

in your form, which will put a hidden True. When the form is posted back to your server the model will now have that value set to True.

在您的表单中,这将放置一个隐藏的 True。当表单回发到您的服务器时,模型现在将该值设置为 True。

It's hard to give much more advice than that as your question isn't specific as to whyyou want to do this. It's perhaps vital that you read a good book on moving to MVC from WebForms, such as Steve Sanderson's Pro ASP.NET MVC.

很难给出比这更多的建议,因为您的问题并不具体说明为什么要这样做。阅读一本关于从 WebForms 迁移到 MVC 的好书可能很重要,例如 Steve Sanderson 的 Pro ASP.NET MVC。

回答by Francis Rodgers

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server"thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

首先,ASP.NET MVC 的工作方式与 WebForms 不同。你没有全部runat="server"。MVC 不提供 WebForms 提供的抽象层。也许您应该尝试了解控制器和动作是什么,然后您应该查看模型绑定。任何关于 MVC 的初级教程都展示了如何在客户端和服务器之间传递数据。

回答by Alexander Beletsky

You are doing it wrong since you try to map WebForms in the MVC application.

因为您尝试在 MVC 应用程序中映射 WebForms,所以您做错了。

There are no server side controlls in MVC. Only the Viewand the Controlleron the back-end. You send the data from server to the client by means of initialization of the View with your model.

MVC 中没有服务器端控件。只有后端的视图控制器。您可以通过使用模型初始化视图来将数据从服务器发送到客户端。

This is happening on the HTTP GET request to your resource.

这发生在对您的资源的 HTTP GET 请求上。

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost]handler in your controller.

您可以通过将数据发布到服务器来将数据从客户端发送到服务器。为了实现这一点,您[HttpPost]在控制器中的视图和处理程序中创建了一个表单 。

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

回答by Alex R.

As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.

正如您可能已经想到的那样,Asp.Net MVC 是与 Asp.Net(webforms)不同的范式。在服务器和客户端之间访问表单元素在 Asp.Net MVC 中采用不同的方法。

You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden", but initialize it with a value from the ViewDataor for Razor, ViewBag.

你可以在网上谷歌搜索更多关于这方面的阅读材料。现在,我建议使用 Ajax 来获取或发布数据到服务器。您仍然可以使用input type="hidden",但使用ViewDataRazor 中的或值初始化它,ViewBag

For example, your controller may look like this:

例如,您的控制器可能如下所示:

public ActionResult Index()
{
     ViewBag.MyInitialValue = true;
     return View();
} 

In your view, you can have an input elemet that is initialized by the value in your ViewBag:

在您看来,您可以拥有一个由您的 中的值初始化的输入元素ViewBag

<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />

Then you can pass data between the client and server via ajax. For example, using jQuery:

然后就可以通过ajax在客户端和服务器之间传递数据了。例如,使用 jQuery:

$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
   // blah
});

You can alternatively use $.ajax, $.getJSON, $.postdepending on your requirement.

您也可以使用$.ajax$.getJSON$.post这取决于你的需求。

回答by Rolice

If you are using Razor, you cannot access the field directly, but you can manage its value.

如果您使用 Razor,则无法直接访问该字段,但可以管理其值。

The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.

这个想法是 Microsoft 的第一个方法驱使开发人员远离 Web 开发,并使桌面程序员(例如)轻松制作 Web 应用程序。

Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.

同时,Web 开发人员并不了解 ASP.NET 这种棘手的奇怪方式。

Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.

实际上,这个隐藏的输入是在客户端呈现的,ASP 无法访问它(它从来没有)。但是,随着时间的推移,您会发​​现它是一种盗版方式,并且当您使用它时,您可能会依赖它。Web 开发不同于桌面或移动。

The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.

模型是你的逻辑单元,隐藏字段(和整个视图页面)只是数据的一个代表视图。因此,您可以将您的工作专用于应用程序或域逻辑,而视图只是将其提供给消费者——这意味着您不需要在视图中进行详细的访问和“头脑风暴”功能。

The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.

控制器实际上可以完成您管理隐藏或常规设置所需的工作。简单地说,模型提供特定的逻辑单元属性和功能,而视图只是将其呈现给最终用户。阅读更多关于MVC 的信息

Model

模型

public class MyClassModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string MyPropertyForHidden { get; set; }
}

This is the controller aciton

这是控制器动作

public ActionResult MyPageView()
{
    MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
    // IList model = new List<MyClassModel>(); // or List, strongly-typed
    // ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag

    return View(model);
}

The view is below

视图如下

//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    // Renders hidden field for your model property (strongly-typed)
    // The field rendered to server your model property (Address, Phone, etc.)
    Html.HiddenFor(model => Model.MyPropertyForHidden); 

    // For list you may use foreach on Model
    // foreach(var item in Model) or foreach(MyClassModel item in Model)
}

// ... Some Other Code ...

The view with ViewBag:

ViewBag 的视图:

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    Html.Hidden(
        "HiddenName",
        ViewBag.MyHiddenInputValue,
        new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
    );
}

// ... Some Other Code ...

We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue">also.

我们正在使用 Html Helper 来渲染 Hidden 字段,或者我们也可以手动编写它<input name=".." id=".." value="ViewBag.MyHiddenInputValue">

The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.

ViewBag 是视图的某种数据载体。它不会限制您使用模型 - 您可以放置​​任何您喜欢的东西。