Using BeginCollectionItem with MVC Core










1















I don't appear to be having the same issues as most with the implementation of BeginCollectionItem with MVC core, I'm not receiving any of the data.



I have this main page that has alot of work on it but here is the javascript that adds new sections to the page and the partial that will be added below.





@model QuizBuilderModel
...
function addSection()
$.ajax(
url: '@Url.Action("AddSection","Quiz")',
cache: false,
success: function (html)
$("#sortable-survey").append(html);

);

...

<div class="quiz-builder" id="quiz-builder" style="@((Model.Quiz == null || string.IsNullOrEmpty(Model.Quiz.Id))? "display: none;" : "")">
@await Html.RenderPartialAsync("~/Views/Admin/Quiz/_QuizBuilder.cshtml", Model);
</div>


Now, we have this partial to start the form we're building.



@model QuizBuilderModel

<div id="sortable-survey" class="sortable-survey">
@using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

@if (Model.Quiz != null && !string.IsNullOrEmpty(Model.Quiz.Id))

<input type="submit" class="btn btn-lg btn-outline-primary top-right-button top-right-button-single" id="SaveQuizModal" name="SaveQuizModal" value="Save Quiz" />


@if (Model.Quiz != null && Model.Quiz.Sections != null)

foreach (Sections section in Model.Quiz.Sections)

await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model);



</div>

<div>
<div class="text-center">
<button type="button" class="btn btn-outline-primary btn-sm my-5" id="AddSection" onclick="addSection();">
<i class="simple-icon-plus btn-group-icon"></i>
Add Section
</button>
</div>
</div>


Then I have this partial section where we'll be adding more and more to it.



@using HtmlHelpers.BeginCollectionItemCore
@model Sections

@using (Html.BeginCollectionItem("Sections"))

<div class="form-group">
@Html.LabelFor(x => x.Title);
@Html.EditorFor(m => m.Title, new @class = "form-control" )
</div>

<div class="form-group">
<label>SubTitle (optional)</label>
@Html.EditorFor(m => m.SubTitle, new @class = "form-control" )
</div>

<div class="form-group">
<label>Instructions (optional)</label>
<textarea type="text" class="form-control" placeholder="" id="Instructions" name="Instructions" required rows="10" cols="50"></textarea>
</div>



The response of the post is sent here...



[HttpPost]
public async Task<IActionResult> PostQuizUpdate(IEnumerable<Sections> Sections)

...



Like i said before when I hit the submit I'm not getting the list of Sections in the post.










share|improve this question
























  • Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

    – user3559349
    Nov 14 '18 at 0:10











  • @StephenMuecke ok I fixed that bug but I'm still getting zero rows.

    – jcaruso
    Nov 14 '18 at 2:33











  • Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

    – user3559349
    Nov 14 '18 at 2:35











  • @StephenMuecke Empty collection... Count(0)

    – jcaruso
    Nov 14 '18 at 2:37











  • The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

    – user3559349
    Nov 14 '18 at 2:40















1















I don't appear to be having the same issues as most with the implementation of BeginCollectionItem with MVC core, I'm not receiving any of the data.



I have this main page that has alot of work on it but here is the javascript that adds new sections to the page and the partial that will be added below.





@model QuizBuilderModel
...
function addSection()
$.ajax(
url: '@Url.Action("AddSection","Quiz")',
cache: false,
success: function (html)
$("#sortable-survey").append(html);

);

...

<div class="quiz-builder" id="quiz-builder" style="@((Model.Quiz == null || string.IsNullOrEmpty(Model.Quiz.Id))? "display: none;" : "")">
@await Html.RenderPartialAsync("~/Views/Admin/Quiz/_QuizBuilder.cshtml", Model);
</div>


Now, we have this partial to start the form we're building.



@model QuizBuilderModel

<div id="sortable-survey" class="sortable-survey">
@using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

@if (Model.Quiz != null && !string.IsNullOrEmpty(Model.Quiz.Id))

<input type="submit" class="btn btn-lg btn-outline-primary top-right-button top-right-button-single" id="SaveQuizModal" name="SaveQuizModal" value="Save Quiz" />


@if (Model.Quiz != null && Model.Quiz.Sections != null)

foreach (Sections section in Model.Quiz.Sections)

await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model);



</div>

<div>
<div class="text-center">
<button type="button" class="btn btn-outline-primary btn-sm my-5" id="AddSection" onclick="addSection();">
<i class="simple-icon-plus btn-group-icon"></i>
Add Section
</button>
</div>
</div>


Then I have this partial section where we'll be adding more and more to it.



@using HtmlHelpers.BeginCollectionItemCore
@model Sections

@using (Html.BeginCollectionItem("Sections"))

<div class="form-group">
@Html.LabelFor(x => x.Title);
@Html.EditorFor(m => m.Title, new @class = "form-control" )
</div>

<div class="form-group">
<label>SubTitle (optional)</label>
@Html.EditorFor(m => m.SubTitle, new @class = "form-control" )
</div>

<div class="form-group">
<label>Instructions (optional)</label>
<textarea type="text" class="form-control" placeholder="" id="Instructions" name="Instructions" required rows="10" cols="50"></textarea>
</div>



The response of the post is sent here...



[HttpPost]
public async Task<IActionResult> PostQuizUpdate(IEnumerable<Sections> Sections)

...



Like i said before when I hit the submit I'm not getting the list of Sections in the post.










share|improve this question
























  • Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

    – user3559349
    Nov 14 '18 at 0:10











  • @StephenMuecke ok I fixed that bug but I'm still getting zero rows.

    – jcaruso
    Nov 14 '18 at 2:33











  • Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

    – user3559349
    Nov 14 '18 at 2:35











  • @StephenMuecke Empty collection... Count(0)

    – jcaruso
    Nov 14 '18 at 2:37











  • The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

    – user3559349
    Nov 14 '18 at 2:40













1












1








1








I don't appear to be having the same issues as most with the implementation of BeginCollectionItem with MVC core, I'm not receiving any of the data.



I have this main page that has alot of work on it but here is the javascript that adds new sections to the page and the partial that will be added below.





@model QuizBuilderModel
...
function addSection()
$.ajax(
url: '@Url.Action("AddSection","Quiz")',
cache: false,
success: function (html)
$("#sortable-survey").append(html);

);

...

<div class="quiz-builder" id="quiz-builder" style="@((Model.Quiz == null || string.IsNullOrEmpty(Model.Quiz.Id))? "display: none;" : "")">
@await Html.RenderPartialAsync("~/Views/Admin/Quiz/_QuizBuilder.cshtml", Model);
</div>


Now, we have this partial to start the form we're building.



@model QuizBuilderModel

<div id="sortable-survey" class="sortable-survey">
@using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

@if (Model.Quiz != null && !string.IsNullOrEmpty(Model.Quiz.Id))

<input type="submit" class="btn btn-lg btn-outline-primary top-right-button top-right-button-single" id="SaveQuizModal" name="SaveQuizModal" value="Save Quiz" />


@if (Model.Quiz != null && Model.Quiz.Sections != null)

foreach (Sections section in Model.Quiz.Sections)

await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model);



</div>

<div>
<div class="text-center">
<button type="button" class="btn btn-outline-primary btn-sm my-5" id="AddSection" onclick="addSection();">
<i class="simple-icon-plus btn-group-icon"></i>
Add Section
</button>
</div>
</div>


Then I have this partial section where we'll be adding more and more to it.



@using HtmlHelpers.BeginCollectionItemCore
@model Sections

@using (Html.BeginCollectionItem("Sections"))

<div class="form-group">
@Html.LabelFor(x => x.Title);
@Html.EditorFor(m => m.Title, new @class = "form-control" )
</div>

<div class="form-group">
<label>SubTitle (optional)</label>
@Html.EditorFor(m => m.SubTitle, new @class = "form-control" )
</div>

<div class="form-group">
<label>Instructions (optional)</label>
<textarea type="text" class="form-control" placeholder="" id="Instructions" name="Instructions" required rows="10" cols="50"></textarea>
</div>



The response of the post is sent here...



[HttpPost]
public async Task<IActionResult> PostQuizUpdate(IEnumerable<Sections> Sections)

...



Like i said before when I hit the submit I'm not getting the list of Sections in the post.










share|improve this question
















I don't appear to be having the same issues as most with the implementation of BeginCollectionItem with MVC core, I'm not receiving any of the data.



I have this main page that has alot of work on it but here is the javascript that adds new sections to the page and the partial that will be added below.





@model QuizBuilderModel
...
function addSection()
$.ajax(
url: '@Url.Action("AddSection","Quiz")',
cache: false,
success: function (html)
$("#sortable-survey").append(html);

);

...

<div class="quiz-builder" id="quiz-builder" style="@((Model.Quiz == null || string.IsNullOrEmpty(Model.Quiz.Id))? "display: none;" : "")">
@await Html.RenderPartialAsync("~/Views/Admin/Quiz/_QuizBuilder.cshtml", Model);
</div>


Now, we have this partial to start the form we're building.



@model QuizBuilderModel

<div id="sortable-survey" class="sortable-survey">
@using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

@if (Model.Quiz != null && !string.IsNullOrEmpty(Model.Quiz.Id))

<input type="submit" class="btn btn-lg btn-outline-primary top-right-button top-right-button-single" id="SaveQuizModal" name="SaveQuizModal" value="Save Quiz" />


@if (Model.Quiz != null && Model.Quiz.Sections != null)

foreach (Sections section in Model.Quiz.Sections)

await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model);



</div>

<div>
<div class="text-center">
<button type="button" class="btn btn-outline-primary btn-sm my-5" id="AddSection" onclick="addSection();">
<i class="simple-icon-plus btn-group-icon"></i>
Add Section
</button>
</div>
</div>


Then I have this partial section where we'll be adding more and more to it.



@using HtmlHelpers.BeginCollectionItemCore
@model Sections

@using (Html.BeginCollectionItem("Sections"))

<div class="form-group">
@Html.LabelFor(x => x.Title);
@Html.EditorFor(m => m.Title, new @class = "form-control" )
</div>

<div class="form-group">
<label>SubTitle (optional)</label>
@Html.EditorFor(m => m.SubTitle, new @class = "form-control" )
</div>

<div class="form-group">
<label>Instructions (optional)</label>
<textarea type="text" class="form-control" placeholder="" id="Instructions" name="Instructions" required rows="10" cols="50"></textarea>
</div>



The response of the post is sent here...



[HttpPost]
public async Task<IActionResult> PostQuizUpdate(IEnumerable<Sections> Sections)

...



Like i said before when I hit the submit I'm not getting the list of Sections in the post.







asp.net-core-mvc begincollectionitem






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 5:04







user3559349

















asked Nov 13 '18 at 17:45









jcarusojcaruso

83812251




83812251












  • Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

    – user3559349
    Nov 14 '18 at 0:10











  • @StephenMuecke ok I fixed that bug but I'm still getting zero rows.

    – jcaruso
    Nov 14 '18 at 2:33











  • Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

    – user3559349
    Nov 14 '18 at 2:35











  • @StephenMuecke Empty collection... Count(0)

    – jcaruso
    Nov 14 '18 at 2:37











  • The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

    – user3559349
    Nov 14 '18 at 2:40

















  • Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

    – user3559349
    Nov 14 '18 at 0:10











  • @StephenMuecke ok I fixed that bug but I'm still getting zero rows.

    – jcaruso
    Nov 14 '18 at 2:33











  • Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

    – user3559349
    Nov 14 '18 at 2:35











  • @StephenMuecke Empty collection... Count(0)

    – jcaruso
    Nov 14 '18 at 2:37











  • The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

    – user3559349
    Nov 14 '18 at 2:40
















Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

– user3559349
Nov 14 '18 at 0:10





Have you shown the correct code? You have a foreach (Sections section ...) line that is passing QuizBuilderModel to a partial that expect Sections which would throw this exception

– user3559349
Nov 14 '18 at 0:10













@StephenMuecke ok I fixed that bug but I'm still getting zero rows.

– jcaruso
Nov 14 '18 at 2:33





@StephenMuecke ok I fixed that bug but I'm still getting zero rows.

– jcaruso
Nov 14 '18 at 2:33













Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

– user3559349
Nov 14 '18 at 2:35





Do you mean your IEnumerable<Sections> Sections parameter in the POST method is null or an empty collection?

– user3559349
Nov 14 '18 at 2:35













@StephenMuecke Empty collection... Count(0)

– jcaruso
Nov 14 '18 at 2:37





@StephenMuecke Empty collection... Count(0)

– jcaruso
Nov 14 '18 at 2:37













The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

– user3559349
Nov 14 '18 at 2:40





The rest of the code look OK, except you should be using @Html.TextAreaFor(m => m.Instructions, new ... ). What is the actual html generated by one of the _Section.cshtml partials

– user3559349
Nov 14 '18 at 2:40












1 Answer
1






active

oldest

votes


















1














Your script is appending the partial containing BeginCollectionItem to the <div id="sortable-survey" class="sortable-survey"> element. But that element contains your <form>....</form> element, so $("#sortable-survey").append(html); will append the html after the closing </form> tag, and as a result, your <form> itself will not contain any form controls, so there is nothing to submit.



Alter the html so that the <div> is within the <form> element





@using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

<div id="sortable-survey" class="sortable-survey">
....
</div>



so that the appended form controls are within the form tags.



As a side note, if your Sections property contains any existing elements, then your await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model); will throw a The model item passed into the dictionary is of type .. but this dictionary requires a model item of type exception. You need to modify the foreach loop to



foreach (Sections section in Model.Quiz.Sections)

await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", section); // section, not Model



In addition, I recommend you initialize your collections in the controller before passing the model to the view so that you can delete the if null checks in the view.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286776%2fusing-begincollectionitem-with-mvc-core%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Your script is appending the partial containing BeginCollectionItem to the <div id="sortable-survey" class="sortable-survey"> element. But that element contains your <form>....</form> element, so $("#sortable-survey").append(html); will append the html after the closing </form> tag, and as a result, your <form> itself will not contain any form controls, so there is nothing to submit.



    Alter the html so that the <div> is within the <form> element





    @using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

    <div id="sortable-survey" class="sortable-survey">
    ....
    </div>



    so that the appended form controls are within the form tags.



    As a side note, if your Sections property contains any existing elements, then your await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model); will throw a The model item passed into the dictionary is of type .. but this dictionary requires a model item of type exception. You need to modify the foreach loop to



    foreach (Sections section in Model.Quiz.Sections)

    await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", section); // section, not Model



    In addition, I recommend you initialize your collections in the controller before passing the model to the view so that you can delete the if null checks in the view.






    share|improve this answer



























      1














      Your script is appending the partial containing BeginCollectionItem to the <div id="sortable-survey" class="sortable-survey"> element. But that element contains your <form>....</form> element, so $("#sortable-survey").append(html); will append the html after the closing </form> tag, and as a result, your <form> itself will not contain any form controls, so there is nothing to submit.



      Alter the html so that the <div> is within the <form> element





      @using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

      <div id="sortable-survey" class="sortable-survey">
      ....
      </div>



      so that the appended form controls are within the form tags.



      As a side note, if your Sections property contains any existing elements, then your await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model); will throw a The model item passed into the dictionary is of type .. but this dictionary requires a model item of type exception. You need to modify the foreach loop to



      foreach (Sections section in Model.Quiz.Sections)

      await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", section); // section, not Model



      In addition, I recommend you initialize your collections in the controller before passing the model to the view so that you can delete the if null checks in the view.






      share|improve this answer

























        1












        1








        1







        Your script is appending the partial containing BeginCollectionItem to the <div id="sortable-survey" class="sortable-survey"> element. But that element contains your <form>....</form> element, so $("#sortable-survey").append(html); will append the html after the closing </form> tag, and as a result, your <form> itself will not contain any form controls, so there is nothing to submit.



        Alter the html so that the <div> is within the <form> element





        @using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

        <div id="sortable-survey" class="sortable-survey">
        ....
        </div>



        so that the appended form controls are within the form tags.



        As a side note, if your Sections property contains any existing elements, then your await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model); will throw a The model item passed into the dictionary is of type .. but this dictionary requires a model item of type exception. You need to modify the foreach loop to



        foreach (Sections section in Model.Quiz.Sections)

        await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", section); // section, not Model



        In addition, I recommend you initialize your collections in the controller before passing the model to the view so that you can delete the if null checks in the view.






        share|improve this answer













        Your script is appending the partial containing BeginCollectionItem to the <div id="sortable-survey" class="sortable-survey"> element. But that element contains your <form>....</form> element, so $("#sortable-survey").append(html); will append the html after the closing </form> tag, and as a result, your <form> itself will not contain any form controls, so there is nothing to submit.



        Alter the html so that the <div> is within the <form> element





        @using (Html.BeginForm("PostQuizUpdate", "Quiz", FormMethod.Post))

        <div id="sortable-survey" class="sortable-survey">
        ....
        </div>



        so that the appended form controls are within the form tags.



        As a side note, if your Sections property contains any existing elements, then your await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", Model); will throw a The model item passed into the dictionary is of type .. but this dictionary requires a model item of type exception. You need to modify the foreach loop to



        foreach (Sections section in Model.Quiz.Sections)

        await Html.RenderPartialAsync("~/Views/Admin/Quiz/_Section.cshtml", section); // section, not Model



        In addition, I recommend you initialize your collections in the controller before passing the model to the view so that you can delete the if null checks in the view.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 4:12







        user3559349


































            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286776%2fusing-begincollectionitem-with-mvc-core%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto