i building small web application asp.net mvc c#. have 2 models:
public class parent { public guid id { get; set; } public virtual icollection<child> children { get; set; } } public class child { public guid id { get; set; } public guid parentid{ get; set; } public virtual parent parent { get; set; } }
and have parentview send parent id child controller actionlink, this:
@html.actionlink("something", "childindexmethod", "childcontroller", new { parentid=item.id}, null)
when clicked, go childindexview , list of children under parent model. there, want able create new child under same parent. create new child need provide parentid new child object. how can retrieve parentid , pass child?
i did this:
if (model.firstordefault() != null) { @html.actionlink("new child", "newchild", new { parentid = model.firstordefault().parentid}) } else { //what if model null? }
first check if model not null. if not null, take firstordefault object model , pass parentid child. works if there children under parent. if there no children under parent, cannot read parentid , error occurs. how can send parentid child element position?
i know wrong method achieve goal. still learning. also, not able find answer on so. appreciated.
thank you
it seems model in children view ienumerable<child>
. have 2 options:
define new viewmodel contains list of child , parentid:
public childlistviewmodel { public guid parentid {...} public ienumerable <child> children {...} }
use view bag
viewbag.parentid = parentid;
both make parentid available in view if don't have child
Comments
Post a Comment