Search code examples
asp.net-mvc-4razor-2

Assigning a Razor var using a Javascript function


On this page, a user fills out a web form, and it gets added to the list when created. I want to filter the list so a logged in user will only see forms they made themselves.

I have some Razor code that runs a foreach loop through all available items, and I have Javascript that rips the currently logged in user's info.

is it possible to assign this data to a var in the razor code?

ex.

@{var user = getUser(); //want something like this }

@foreach (var item in Model) {


    //add check if item.name == user.name here

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.name)
            </td>
           etc etc

<script> 
    function getUser() {$.getJSON('GetLoggedUserInfo', function(data) {
         return data;
     });
</script>

Solution

  • I do not think it is a good idea to have this logic in a view. View should be as 'dumb' as possible. You could make item filtering at data storage level or at least in controller:

    return View(items.Where(x => x.name == user.name))