如何根据父键预先选择下拉选项列表

时间:2022-07-23 14:30:10

I have two entities Rack and Server. Where each server has a foreign key to the parent rack. Currently I am assigning a server to a Rack, using a drop down list as follow inside the server create view. The Server Create action method looks as follow:-

我有两个实体Rack和Server。每个服务器都有父机架的外键。目前我正在使用服务器创建视图中的下拉列表为服务器分配服务器。 Server Create操作方法如下所示: -

public ActionResult Create()
        {
            PopulateViewBagData();

            return View(new ServerJoin() { IsIPUnique = true,
            IsMACUnique = true});
        }

Part of the server create view which include a drop down list to select the Rack as follow:-

服务器的一部分创建视图,其中包含一个下拉列表以选择Rack如下: -

@model TMS.ViewModels.ServerJoin
<div>
   <span class="f"> Rack</span>

    @Html.DropDownListFor(model =>model.Server.RackID, ((IEnumerable<TMS.Models.TMSRack>)ViewBag.Racks).Select(option => new SelectListItem {
        Text = (option == null ? "None" : option.Technology.Tag), 
        Value = option.TMSRackID.ToString(),
        Selected = (Model.Server != null) && (option.TMSRackID == Model.Server.RackID)
    }), "Choose...")
    @Html.ValidationMessageFor(model =>model.Server.RackID)
</div>

What I am trying to implement , is that Inside the rack view I want to add a link to add a server, and to force the Rack drop down list to select the current Rack , something such as:-

我想要实现的是,在机架视图中我想添加一个链接来添加服务器,并强制机架下拉列表选择当前机架,例如: -

@HTML.Actionlink(“Create Server under this rack”, “Create”,”Server”, new {rackID = Model.RackID},null)

But I am not sure how to force the drop down list to select the rackID passed, baring in mind that the user can still create a server without going to a Rack, the rackID will be null??

但我不确定如何强制下拉列表选择传递的rackID,记住用户仍然可以创建服务器而无需进入Rack,rackID将为null?

Any idea how to implement this ? BR

知道如何实现这个吗? BR

1 个解决方案

#1


1  

Here is how you should do it:

这是你应该怎么做:

public ActionResult Create(int? rackID)
{
    var model = new ServerJoin() { IsIPUnique = true, IsMACUnique = true};
    if(rackID.HasValue)
    {
       model.RackID = rackID.Value;
    }
    PopulateViewBagData();

    return View(model);
}

Then, in your View, you can use an if clause to replace the DropDownList with a Hidden input if the Model has a RackID.

然后,在View中,如果Model具有RackID,则可以使用if子句将DropDownList替换为Hidden输入。

The ActionLink in your Rack View is correct.

Rack View中的ActionLink是正确的。

#1


1  

Here is how you should do it:

这是你应该怎么做:

public ActionResult Create(int? rackID)
{
    var model = new ServerJoin() { IsIPUnique = true, IsMACUnique = true};
    if(rackID.HasValue)
    {
       model.RackID = rackID.Value;
    }
    PopulateViewBagData();

    return View(model);
}

Then, in your View, you can use an if clause to replace the DropDownList with a Hidden input if the Model has a RackID.

然后,在View中,如果Model具有RackID,则可以使用if子句将DropDownList替换为Hidden输入。

The ActionLink in your Rack View is correct.

Rack View中的ActionLink是正确的。