开发者

How to compare a value coming from viewmodel with the textbox value in a foreach loop in view page

开发者 https://www.devze.com 2023-01-29 09:10 出处:网络
In my view page, I am iterating through all the categories coming from model and check with the input value and if matches should display that value in a label.

In my view page, I am iterating through all the categories coming from model and check with the input value and if matches should display that value in a label.

I need some thing like this.

<% foreach(var v in Model.Categories)
  {
      if(v.CategoryId== %>

             $("#TextBox1").val()
      <% ) %>
          $("#Label1").val() =  $("#TextBox1").val();

<% } %>

Can any one 开发者_StackOverflowplease help me how to do it? I do not know if I can use javascript next to <% foreach(var v in Model.Categories) { if(v.CategoryId== %> block


I think your code doesn't make sense for me. Since <% %> will execute on the server side and $("#") jquery will be executed on the client side. In your case I assume that your view already knows the textbox value before it response to the client. you can simply put the textbox value in the ViewData[""] and do something like this:

<% foreach(var v in Model.Categories) {%>
  <% if(v.CategoryId == View["TextboxValue"].ToString()) {%>
    <label><%=View["TextboxValue"].ToString()%></label>
  <% } %>
<% } %>

Besides, If you want to assign for label in jQuery, you should assign by $("#labelname").html("your value");

Any questions, please let me know!!

======================================================================================= Below is my new answer for the question. Then all you need is pure client-side script.

Assume I have a select list like this which's generated from Server-side:

<select id="mylist">
    <option value="1" selected>a</option>
    <option value="2">b</option>
</select>

And also have a textbox and a label:

<input id="tb" value="" type="textbox" />
<label id="lb"></label>

What you need to do is:

<script type="javascript">
    $(document).ready(function(){
         $("#tb").change(function(){
               if($(this).val()==$("#mylist").val())    
                    $("#lb").html($("#mylist").val();
               //you also can do this by getting .text()
               //while val() = [1,2] , text() = [a,b]
         });
    });
</script>

Hope this help!

0

精彩评论

暂无评论...
验证码 换一张
取 消