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.
-
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.Dimitar Dimitrov– Dimitar Dimitrov2013-05-23 18:36:08 +00:00Commented 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.John Edwards– John Edwards2013-05-23 18:50:47 +00:00Commented 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.Dimitar Dimitrov– Dimitar Dimitrov2013-05-23 18:54:04 +00:00Commented 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.John Edwards– John Edwards2013-05-23 19:11:02 +00:00Commented May 23, 2013 at 19:11
Add a comment
|
1 Answer
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>
1 Comment
Th1sD0t
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>)?