How to access .net MVC ViewData from Jquery directly
asp.net-mvc, c#, jquery
Solution
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:
<%
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>
Problem
I am passing viewdata into my aspx page like so: ``` //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. The 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 hook up Jquery to detect the drop-down changes which work, but how do I manipulate the input boxes with data? ``` <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)