1

I have an array of string which I want to show a separate Textbox for each one of them in the View.

I tried to use it like this (which Items is of type string[]):

@foreach(var x in Model.Items) {<input asp-for="x" />}

But this does not work. I can of course go the old way:

 @foreach(var x in Model.Items) {<input name="items" value="x" />}

but I want to know how to do it MVC way.

3
  • 1
    Use a for loop and asp-for="Model[i]" (could also use asp-for=@x" since its string[]) Commented Aug 1, 2017 at 22:26
  • Use enumerables to store in modelview. You could Also use displayfor method am mvc iterate automaticaly and print like a foreach. blog.rodhowarth.com/2011/03/… Commented Aug 1, 2017 at 22:30
  • @StephenMuecke this worked very great for me. thanks a lot. Commented Aug 1, 2017 at 22:35

1 Answer 1

1

For MVC, I would highly recommend putting the string array inside a viewmodel:

public class SomeViewModel
{
   public string[] Items { get; set; }
}

And then point the model to SomeViewModel. And, in the UI, do:

@for (var i = 0; i < Items.Length; i++) {
   <input name="@Html.NameFor(m => m.Items[i])" value="@Model.Items[i]" />
}

or use Html.TextBoxFor(m => m.Items[i]) as an alternative to client-side input.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.