How to access .net MVC ViewData from jQuery directly

I pass viewdata to my aspx page as follows:

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

I populate the drop-down username that I want to associate with jQuery so that when the user changes the drop-down value, this in turn updates the input fields with the currently selected user.

ASPX page:

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

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

I plug in jQuery to detect flush changes that work, but how can I manipulate data input fields?

<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 everything completely wrong? Can you indicate what is best for this scenario. If I can avoid the reverse gear, which would be ideal.

Soul (new to MVC)

+3
source share
3

, javascript #, , javascript , # . , , 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>
+6

javascript. , , . , script (, , , , ), , jQuery.

, .

, :

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

, script, messy:

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

, , :

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

, , , jQuery val() , .

!

+1

You can always update your action.

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

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

Source: https://habr.com/ru/post/1720571/


All Articles