0

I have a Model with Child model.

 [Table("Personnel")]
public class Personnel
{
  [Key]
  public int Id { get; set; }

  [MaxLength(10)]
  public string Code { get; set; }

  [MaxLength(20)]
  public string Name { get; set; }
  public virtual List<PersonnelDegree> Degrees
  {
        get;
        set;
  }

}
public class PersonnelDegree
{
 [Key]
 public int Id { get; set; }

 [ForeignKey("Personnel")]
 public int PersonnelId { get; set; }
 public virtual Personnel Personnel { get; set; }

 [UIHint("Enum")]
 public Degree Degree { get; set; }

 public string Major { get; set; }

 public string SubField { get; set; }

 public string Location { get; set; }
}

I want to created a view for this.(Add)

I added pesonnel field to view, but how to add items for PersonnelDegree?

  @using (Html.BeginForm("Add", "Personnel", FormMethod.Post, new {enctype = "multipart/form-data", @class = "form-horizontal tasi-form", id = "default"}))
    {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary(true, null, new {@class = "alert  alert-danger "})

   <div class="form-group">
    @Html.LabelFor(m => m.Code, new {@class = "control-label col-lg-1"})
    <div class="col-lg-3">
    @Html.TextBoxFor(m => m.Code, null, new {@class = "form-control", maxlength = 10})
    @Html.ValidationMessageFor(m => m.Code)
    </div>
    </div>
    <div class="form-group">
    @Html.LabelFor(m => m.Name, new {@class = "control-label col-lg-1"})
    <div class="col-lg-3">
    @Html.TextBoxFor(m => m.Name, new {@class = "form-control", maxlength = 20})
    @Html.ValidationMessageFor(m => m.Name)
    </div>
    @Html.LabelFor(m => m.Family, new {@class = "control-label col-lg-1"})
    <div class="col-lg-3">
    @Html.TextBoxFor(m => m.Family, null, new {@class = "form-control", maxlength = 30})
    @Html.ValidationMessageFor(m => m.Family)
    </div>
    </div>

Can i add multy PersonnelDegrees in this View?

Edit

I add a div in view for Degrees

 <div id="Degrees">
  <div id="NewDegree" style="display:none">
  <div class="form-group">
    <input class="form-control" id="Degrees[#].Major"   name="Degrees[#].Major" value="" type="text">
          // another items                             
  </div>
  </div>
 </div>

and in javascript :

$(document).ready(function() {
        $(function() {
            $("#addItem").click(function () {
                var index = $('#Degrees tbody tr').length; // assumes rows wont be deleted
                var clone = $('#NewDegree').html();
                // Update the index of the clone
                clone.replace(/\[#\]/g, '[' + index + ']');
                clone.replace(/"%"/g, '"' + index + '"');
                $('#Degrees').append(clone);
            });


        );
    });

it add a div ,But after a few seconds hide div and refresh page.

ar.gorgin
  • 4,765
  • 12
  • 61
  • 100
  • 1
    To render existing `PersonnelDegree` objects you need a `for` loop `EditorTemplate`. To add new `PersonnelDegree` objects you can dynamically add/delete then using javascript/jquery. Refer examples [here](http://stackoverflow.com/questions/24026374/adding-another-pet-to-a-model-form/24027152#24027152) and [here](http://stackoverflow.com/questions/26314077/passing-collection-as-model-without-ordered-index/26314136#26314136) –  Jan 17 '15 at 11:16
  • Thanks a lot, How to send this to controller? – ar.gorgin Jan 18 '15 at 05:56
  • 1
    If you model is `Personnel` and your post method is `public ActionResult Create(Personnel model)` then the model will be bound correctly –  Jan 18 '15 at 06:06
  • The key is binding a collection is to ensure you controls are correctly named and indexed for binding, so you you need controls such as `` etc. –  Jan 18 '15 at 07:25
  • Thanks, i add a div with display:none and add all item (Degrees[#].Name) , but when i add this div in Degrees div (append) , load page again add remove new div. – ar.gorgin Jan 18 '15 at 07:57
  • Note clear what your saying. I suggest you post some code showing what you have tried and what the issue is. –  Jan 18 '15 at 08:00
  • Not sure what your mean by _But after a few seconds hide div and refresh page_? - there is nothing in the code you have posted that would do that. Side note: check what `var index = $('#Degrees tbody tr').length` returns - your element with `id="Degrees" is a `
    ` not a `` so this is probably always `0` so you will be creating duplicate names and id's.
    –  Jan 18 '15 at 08:15
  • Thanks, replace div with table and add it, but how to replace [#] with index? – ar.gorgin Jan 18 '15 at 08:30
  • That depends if you are also allowing rows to be deleted. If not, then get then get the length of the items, otherwise you need to include a hidden input with `name="Index"` and ensure the index value is unique (e.g. `var index = (new Date()).getTime();)`. Spend some time studying the links I gave in my first comment (including the comments in those answers). If you still having problems post a new question with the full details of the view and the scripts. –  Jan 18 '15 at 08:37
  • Thanks a lot :) , i edit my jquery : ` $('#Degrees').append(clone.html());` – ar.gorgin Jan 18 '15 at 10:03

2 Answers2

0

Yes, you can. There are several options how to do it:

Use Js grid-like component

Use some js grid component, i prefer jqgrid you can add data localy on your View with it and then serialize it on form POST to controller.

Advantage: You don't need to write js CRUD operations with your grid your self the only thing that you should get is how to serialize local data right way to controller.

Disadvantage: You should learn how component works and could be that some component not easy emplimentable in MVC project (I mean you could lost your model validation, data annotation etc. on client side)

Add markup with js

Write your own js to resolve this issue. Here is good basic example how to do it. The idea that you generate html with js(get js from controller) and add it to your View.

Advantage: You could do what ever you want is you know js.

Disadvantage: You lost your model validation, data annotation etc. on client side.

Use PartialView with js

Get markup from Controller with Ajax (PartialView for your PersonnelDegree) and attach it to your View with js.

Advantage: You can use all ViewModel advandages (DataAnnotations) plus you can add some tricki logic in your CRUD controller methods if you need. Also it's the most easy maintainable solution if your Project is big and have losg life cicle.

Disadvantage: You should learn how to init client side validation when markup comes from ajax call. Also usually this approach force you to write a lot of code.

I prefer last option if i have a time for this.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Thanks a lot, If i use partial view , How can send list of date in Partialview to main controller? – ar.gorgin Jan 18 '15 at 05:51
  • This [example](http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/) that i already provided in answer is exatly what you need Ajax call get view and that add html that view produced to DOM – teo van kot Jan 18 '15 at 12:27
0

you can add items for PersonnelDegree using partial views. for adding multy PersonnelDegrees in this View you need to create objects in the controller

        Personnel pers = new Personnel(); 
        PersonnelDegrees pr_obj = new PersonnelDegrees ();
        ind_obj.PersonnelDegrees .Add(pr_obj );
        PersonnelDegrees pr_obj1 = new PersonnelDegrees ();
        ind_obj.PersonnelDegrees .Add(pr_obj1 ); 
Ajay Joseph
  • 106
  • 1
  • 7