0

I am very new to MVC, and I would like to have an Add button that adds the text in a text box to a list. I am very lost on how to go about doing this. Thanks.

4
  • I suggest you look into some javascript (possibly jQuery, if you want it to be easier), that should be pretty trivial. Try something then come back and ask something concrete. Commented May 23, 2013 at 18:36
  • So you would say that it is usually better to do those kinds of task client side than using MVC? And also, if I used JQUERY, how would I get the items from that list back into my MVC model? Thanks. Commented May 23, 2013 at 18:50
  • Well, you don't need to hit the server everytime you want to do something as simple as adding a text from a text box to a list. Doing this on the client side is much easier. After the fact, posting your form data to the controller action is irrelevant (since it's not affected by HOW you got this data in your list). I hope I'm making sense. Commented May 23, 2013 at 18:54
  • I understand what you're saying, and that makes sense. I guess I was just confused about how all the items of a complex type like a list box would get submitted. Thanks. Commented May 23, 2013 at 19:11

1 Answer 1

1

I believe this may be what you are after. Please know that the JavaScript depends on including the JQuery library.

<input type="text" id="my-textbox">
<select id="my-listbox">
  <option>Option 1</option>
  <option>Option 2</option>
</select>
<a href="javascript:void(0)" class="action-add-to-list>Add Text To List</a>

<script>
    $('.action-add-to-list').click(function () {
        var newListValue = $('#my-textbox').val();
        if ($.trim(newListValue) != '')
        {
            $('#my-listbox').append('<option>' + newListValue + '</option>');
            $('#my-textbox').val('');
        }
    });
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

This exactly addresses my problem except one thing - is there a possibility to transfer all options as "complex object" (an object that has got one property called "Name") to my Controller (as Nested List<ComplexObject>)?

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.