0

Is there a way to update a model item, while also adding a new item to one of it's properties at the same time?

Let's say I have the following Models:

public class Article
{
    public string ArticleName { get; set; }
    public string ArticleText { get; set; }
    public virtual ICollection<ArticleNotes> ArticleNotes { get; set; }
}

public class ArticleNotes
{
    public string ArticleNote { get; set; }
}

And the following view:

@model MyApp.Models.Article
@using (Html.BeginForm("Article", "Article", FormMethod.Post))
{
    @Html.EditorFor(model => model.ArticleName)
    @Html.EditorFor(model => model.ArticleText)
    <button id="btnSave" name="Submit" type="submit"  value="Save" >Save</button>       
}

Is there a way in this same view to also save a new ArticleNote?

I know I could create a model that holds both a Article property and a separate ArticleNote property, but I wanted to see if I could do something else since I already have a collection of type ArticleNote in Article already. Thanks.

AnotherDeveloper
  • 1,242
  • 1
  • 15
  • 36
  • [This answer](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) may help you to understand how to dynamically add collection items in a view. –  May 22 '15 at 23:27

3 Answers3

1

You can do this, but ASP.NET expects the name of the inputs to be defined in a particular way. In your case you would want your rendered HTML to look like:

<input type="text" name="ArticleNotes[0].ArticleNote" />

When this data gets sent to the server, the model binding will know that it's a related collection and populate the model. An article by Phil Haack still seems to be the definitive source on this feature.

Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
1

You can do something like:

@model MyApp.Models.Article
@using (Html.BeginForm("Article", "Article", FormMethod.Post))
{
    @Html.EditorFor(model => model.ArticleName)
    @Html.EditorFor(model => model.ArticleText)
    var noteInputName =  ViewData.TemplateInfo.GetFullHtmlFieldName("ArticleNotes") + "[0].ArticleNote";

    <input type-"text" name="@noteInputName" value=""/>
    <button id="btnSave" name="Submit" type="submit"  value="Save" >Save</button>       
}
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
1

You can do something like:

@model MyApp.Models.Article

@{
int counter = 0;
}

@using (Html.BeginForm("Article", "Article", FormMethod.Post))
{
@Html.EditorFor(model => model.ArticleName)

@Html.EditorFor(model => model.ArticleText)

<input ArticleNotes[@counter]_ArticleNote" name="ArticleNotes[@counter].ArticleNote" value="" type="text" />

<button id="btnSave" name="Submit" type="submit"  value="Save" Save</button>       

}

you can use your ArticleNotes property like as

public virtual List<ArticleNotes> ArticleNotes { get; set; }

in Article class

Hopefully this your help you.

zaman
  • 145
  • 7