Is there a way to use jquery code inside a razor?

Here is my jQuery code with Razor:

$("#GroupC_grup_name").attr('value', '@foreach (SelectListItem sel in (SelectList)ViewData["Gruplar"]){ @sel.Text }') $("#GroupC_id").attr('value', '@foreach(SelectListItem sel in (SelectList)ViewData["Gruplar"]){ @sel.Value }') 

I want to combine them together since I do not want to call ViewData["Gruplar"] twice.

Can I do something like this?

  @foreach(SelectListItem sel in (SelectList)ViewData["Gruplar"]){ @:$("#GroupC_grup_name").attr('value', '@sel.Text'); @:$("#GroupC_id").attr('value', '@sel.Value'); } 

I tried everything that I could, but I can’t achieve what I want.

+7
source share
3 answers

I carefully read it and realized what you want to do. However, your example is something that is misleading. (it seems everyone answered)

What you did in the second example should work fine, you can wrap your jQuery in a <text></text> element if that helps. If only one value you could just

 <script type='text/javascript'> @{ var x = ((SelectList)ViewData["Gruplar"]).First(); } $("#GroupC_grup_name").attr('value', '@x.Text'); $("#GroupC_id").attr('value', '@x.Value'); </script> 

There are several ways you could execute a razor in jquery. This is basically the same as an html razor.

That you want to perform a razor on the client side, then it does not happen. Razor is executed before it is sent to the client.

+9
source

The code you suggest should work, the code below uses a string array instead of SelectList , but the principle should be the same, the code below has been tested and works -

 @{String[] testarr = {"hello","bye"};} @foreach(String sel in testarr){ @:$("#GroupC_grup_name").attr('value', '@sel'); @:$("#GroupC_id").attr('value', '@sel'); } 
+5
source

As I understand it, do you want to update elements when a SELECT element is selected?

Create a regular picklist and add the following jquery code:

 <script type="text/javascript"> $(function () { $('#selectListId').change(function() { $selectedItem = $("option:selected", this); $("#GroupC_grup_name").val(selectedItem.html()); $("#GroupC_id").val(selectedItem.val()); }); }); </script> 
+1
source

All Articles