C# 如何直接从 Jquery 访问 .net MVC ViewData

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1594958/
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-06 19:09:38  来源:igfitidea点击:

How to access .net MVC ViewData from Jquery directly

c#jqueryasp.net-mvc

提问by soul

I am passing viewdata into my aspx page like so:

我将 viewdata 传递到我的 aspx 页面,如下所示:

//Controller
List<user> userList = Data.GetAllUsersForCompany(companyId);
List<SelectListItem> dropDownList = FormatUserList(userList);
ViewData["UserList"] = userList;
ViewData["FormattedUserList"] = dropDownList;
return View();

I am populating a drop down with the name of a user, which I want to bind with Jquery so that when the user changes the drop down this in turn updates the input fields with the current selected user.

我正在使用用户名填充下拉列表,我想将其与 Jquery 绑定,以便当用户更改下拉列表时,这又会使用当前选定的用户更新输入字段。

The ASPX page:

ASPX 页面:

<p>
  <%= Html.DropDownList("userSelected", (List<SelectListItem>)ViewData["FormattedUserList"] )%><br /><br />

  <%= Html.TextBox("userFName")%><br />
  <%= Html.TextBox("userLName")%><br />    
  <%= Html.TextBox("userEmail")%>
</p>

I hook up Jquery to detect the drop-down changes which work, but how do I manipulate the input boxes with data?

我连接了 Jquery 以检测有效的下拉更改,但是如何使用数据操作输入框?

<script type="text/javascript">
  $(document).ready(function() {
    $("#userSelected").change(function() {
      var pkUser = $("#userSelected").val();
      alert("Current UserID is " + pkUser); //works up to here just fine
      $("#userFName).val() = ViewData["UserList"].Select(x => x.pkUser == valueOfDropDown).fName; ???
      .
      .
      .
    });
  });
</script>

Am I doing things completely wrong? Can you point out what the best practice is for this scenario. If I can get away from having postbacks that would be ideal.

我做的事情完全错误吗?您能否指出这种情况的最佳实践是什么。如果我可以摆脱回发,那将是理想的。

Soul (MVC newbie)

灵魂(MVC新手)

采纳答案by scmccart

It looks like you are mixing your javascript and c#, remember that the javascript only executes client side, and the c# only executes server side. That being said, if you want to have some of your viewdata hanging around for your javascript to use on the client side, you need to encode it in the page somewhere the javascript can get at it. The easiest way I can think of is to use a JavaScriptSerializer and embed the values into your javascript, kind of like:

看起来你正在混合你的javascript和c#,记住javascript只执行客户端,c#只执行服务器端。话虽如此,如果您想让您的 javascript 在客户端使用一些视图数据,您需要将其编码在页面中 javascript 可以获取的位置。我能想到的最简单的方法是使用 JavaScriptSerializer 并将值嵌入到您的 javascript 中,有点像:

<%
  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>

<script type="text/javascript">
  var users = <%= serializer.Serialize(ViewData["UserList"]) %>;

  //Use the users variable now with a copy of the view data.
</script>

回答by Alex Sexton

In most cases, it is better to have static javascript files. It's not universally the case, but its often very hard to manage code that's parsed together at runtime. So rather than trying to write serverside code in your script tags (like the line that seems to be breaking), you should try writing the data to a hidden part of the page, perhaps, and then getting that data with jQuery.

在大多数情况下,最好有静态 javascript 文件。情况并非普遍如此,但通常很难管理在运行时一起解析的代码。因此,与其尝试在脚本标记中编写服务器端代码(例如似乎要中断的行),不如尝试将数据写入页面的隐藏部分,然后使用 jQuery 获取该数据。

You should be able to output a hidden form element with the value of any data that you want to use later on.

您应该能够输出一个隐藏的表单元素,其中包含稍后要使用的任何数据的值。

Say your output was:

假设你的输出是:

<input type="hidden" id="fname_store" name="fname" value="soul" />

This could also be a single variable that is set in an inline script if you find this method messy:

如果您发现此方法混乱,这也可能是在内联脚本中设置的单个变量:

<script type="text/javascript">
   var data = <% serialized_data_from_the_server_side %>;
</script>

Then your line that breaks would be something like this:

那么你的断线将是这样的:

$('#userFName').val($('#fname_store').val());

Notice that you are missing a quote in your code at the end of the selector, and also notice that the jQuery val() function is set by passing it a value, not setting it equal to a value.

请注意,您在选择器末尾的代码中缺少引号,还要注意 jQuery val() 函数是通过向它传递一个值来设置的,而不是将它设置为等于一个值。

Best of Luck!

祝你好运!

回答by Daniel A. White

You can always update your Action.

您可以随时更新您的操作。

List<user> userList = Data.GetAllUsersForCompany(companyId);
List<SelectListItem> dropDownList = FormatUserList(userList);

return Json(new { UserList = userList, FomattedUserList = dropDownList} );