0

I'm developing an ASP.NET MVC 5 application with Razor, C# and .NET Framework 4.7.

I have this code on my View:

@for (int index = 0; index < Model.LevelsGtin.Count; index++)
{
    <tr>
        <td>@Html.TextBoxFor(m => m.LevelsGtin[index].Level, new { @disabled = "disabled" })</td>
        <td>@Html.TextBoxFor(m => m.LevelsGtin[index].Gtin )</td>
    </tr>
}

If I want to let user to add more elements into Model.LevelsGtin.

I've been using JavaScript to clone that <tr> ... </tr>, but the code is very messy, and I think that maybe there is a better way to do it (at least an easier one).

Is there anyway to do it with C# code?

I don't know if there is something in the ASP.NET MVC framework that let add more elements into an array: like a magical add button that adds an element into the Model.LevelsGtin.

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • without using javascript and added javascript tag ?? – Akhil Aravind Jul 17 '18 at 06:43
  • What's your current javascript code? – D-Shih Jul 17 '18 at 06:54
  • @D-Shih Sorry, I'm not going to show you my Javascript code because it is irrelevant for my question. I'm not trying to modify my current code, I'm asking about if there is something in ASP.NET MVC framework that let me add more elements into a model's array. – VansFannel Jul 17 '18 at 07:00
  • 2
    That is simply not possible unless you where to post back to the server to add a new item and redirect back again (c# runs on the server not the browser) –  Jul 17 '18 at 07:12
  • For some options using javascript, refer [this answer](https://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) and [this one](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) for a more detailed implementation using `BeginCollectionItem` –  Jul 17 '18 at 07:21
  • javascript for client side, c# for server side, the nearest thing to what you want to achieve perhaps is use ajax to call server side code that return partial view. Then append the partial view to your table. but you cant do it without javascript. – Ppp Jul 17 '18 at 07:41
  • @StephenMuecke that is true in that case but not in general. Have you seen DNA (dot net anywhere) been launched inside a browser? I have :P https://www.youtube.com/watch?v=MiLAE6HMr10&t=2445s – SOReader Jul 21 '18 at 22:11

0 Answers0