简体   繁体   中英

Why Does my Javascript Function Run on Load

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.

@(Model.Ingredients).Add(ingredientArray[i]);

is a server side script which will be executed when the view is prepared. So this line will be executed when you load the page. And that is why you are getting null reference error, because Model.Ingredients is not yet initialized.

It looks like @Model == null. You have to pass the model instance to the view:

return View(model);

And you can't mix the JavaScript client-side code with the server-side Razor code (in the way you do it). It'll not work.

This might be helpful: Mix Razor and Javascript code or Mixing JavaScript and Razor syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM