Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use jquery code inside 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 merge these together, as in I dont want to call for 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've tried everything I can think of but still can't achieve what I want.

like image 303
Berker Yüceer Avatar asked Oct 20 '11 11:10

Berker Yüceer


1 Answers

I read it carefully and understand what you want to do. However your example is what is confusing. (it seems to everyone that answered)

What you've done in the second example should work just fine you could wrap your jQuery in a <text></text> element if that helps as well. If there's only ever 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 any number of ways you could accomplish razor within jquery. It's basically the same as razor with html.

It you want to execute razor on the client side then that's not going to happen. Razor is executed before it gets sent to the client.

like image 64
Buildstarted Avatar answered Sep 17 '22 15:09

Buildstarted