I have this code on my Create view.
<div class="col-lg-6">
<!--Ingredients-->
@Html.LabelFor(model => model.Ingredients, htmlAttributes: new { @class = "control-label col-md-2" })<br />
<textarea class="form-control" id="ingredients" rows="20" onsubmit="PopulateIngredients()"></textarea>
</div>
<script>
function PopulateIngredients()
{
var ingredientArray = document.getElementById('ingredients').val().split('/n');
if (ingredientArray.length !=0)
{
for (i = 0; i < ingredientArray.length; i++)
{
@(Model.Ingredients).Add(ingredientArray[i]);
}
}
}
</script>
When the page is loading I get an error in the script saying "Object reference not set to an instance of an object." at this line;
@(Model.Ingredients).Add(ingredientArray[i]);
Two problems exist. One is that I should be seeing the model.Ingredients IEnumerable object. Two is that his script shouldn't run until the submit button is clicked.
What am I doing wrong? I have to use a text area for input so I have to split it and add it to the ingredient list before it is posted back to the controller where it is handled as a list of ingredient objects. I did not include the classes for brevity.