0

I Have a Input tag in Html :

 <div class="form-group col-md-5">                           
     <input asp-for="CountSlide" class="form-control" value="2"/>                      
     <a id="add-slide" class="btn btn-info m-t-5" href="#">Add</a>
 </div>

And I Have A Loop in Razor View :

@for (int i = 0; i < count; i++)
       {
         <div class="form-group">                               
           <input type="file" onchange="readURL(this);" class="form-control">                                
         </div>
       }

I want to use the input value in the loop ("count") when the add button is clicked?

sunboy_sunboy
  • 225
  • 2
  • 14
  • If my reply is helpful, please accept it as answer(click on the mark option beside the reply to toggle it from greyed out to fill in.), see https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jason Pan Aug 30 '21 at 06:15

1 Answers1

1

NEWEST

You can put your @for code in partial view.

enter image description here

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project


You want the following div in @for (int i = 0; i <count; i++) to render elements according to the value in the input, which is impossible.

You only can do it by javascript, not use razor engine.

Related Post: What is the order of execution of the C# in Razor

The simple explanation is that when you can see all the contents of the page, the back-end C# code will no longer be executed.

PRIVIOUS

You can use @count to get the value.

enter image description here

@{
    ViewData["Title"] = "Home Page";
    int count = 5;
}
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>

<script>
    function readURL(url) {
        alert(url)
    }
    function func() {
        var get_count = @count;
        alert(get_count);
        //$.ajax({
        //    url: "url",
        //    type: "POST",
        //    data: {a:"a"},
        //    success: function (veri) {
        //        console.log("success");
        //    },
        //    error: function (hata, ajaxoptions, throwerror) {
        //        alert("failed");
        //    }
        //});
    }

</script>

<div class="form-group col-md-5">
    <input  class="form-control" value="2" />
    <a id="add-slide" class="btn btn-info m-t-5" href="#"  onclick="func()">Add</a>
</div>

<hr />

@for (int i = 0; i < count; i++)
{
    <div class="form-group">
        <input type="file" onchange="readURL(this);" class="form-control">
    </div>
}
Jason Pan
  • 15,263
  • 1
  • 14
  • 29