ASP.NET MVC在控制器中为视图设置默认值

时间:2015-11-24 23:30:22

标签: c# asp.net asp.net-mvc asp.net-mvc-4

原谅我,我只是在学习mvc。我有一个管理项目和实用程序的应用程序。对于每个项目,可以有多个实用程序。有一个" Projects"列出所有项目的页面,如果单击项目,它将列出与其关联的所有实用程序。项目屏幕上还有一个按钮,允许您将Utilities添加到该项目。因此,当您单击项目然后单击"添加实用程序"按钮,它会拉出一个表单,以允许您向该项目添加实用程序。表单具有项目ID,实用程序ID和所有者预填充,取自项目控制器信息。我想要做的是在Utility(重定位费用)中的一个字段上设置默认值为0.00。因此,如果用户没有更改它,它在数据库中显示为0.00。看起来很简单,对吧?

这是我目前在控制器的Get方法的控制器中的代码(来自前一个线程的建议)以及我将其更改为的内容。

在:

 // GET: /Utility/Create
        public ActionResult Create(int? ProjectID)
        {
            CreateDropDownListForCreateOrEdit(ProjectID);
            return View();
        }

之后:

public ActionResult Create(int? ProjectID)
{
    CreateDropDownListForCreateOrEdit(ProjectID);
    // initialize the model and set its properties
    UtilityDTO model = new UtilityDTO
    {
        Est_Relocation_Expense = 0M
    };
    // return the model
    return View(model);
}

我的观点如下:

@Html.TextBoxFor(model => model.Est_Relocation_Expense, "{0:0.00}")

这很有用......它将默认值添加到字段中......但是,它丢失了从项目中检索到的预填充项目ID,实用程序ID和所有者信息(不预先填充)控制器。

有谁知道这里可能有什么问题?如果需要的话,我也可以从控制器提供其他代码,但它很长,所以不确定还有什么要发布。

为项目ID添加了视图:

<div class="form-group">
                    @Html.LabelFor(model => model.Project_ID, new { @class = "control-label col-md-2 CreateEditFieldNamesSpan" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(model => model.Project_ID, (SelectList)ViewBag.VBProjectIDAndName, "---Select Project---")
                        @Html.ValidationMessageFor(model => model.Project_ID)
                    </div>
                </div>

1 个答案:

答案 0 :(得分:1)

在将模型传递给视图之前,需要在模型中设置属性的值。您目前仅设置Est_Relocation_Expense的值。如果您希望下拉列表在方法中显示与ProjectID参数关联的选项,请将方法修改为

public ActionResult Create(int? ProjectID)
{
    CreateDropDownListForCreateOrEdit(ProjectID);
    UtilityDTO model = new UtilityDTO
    {
        Project_ID = ProjectID, // add this
        Est_Relocation_Expense = 0M
    };
    return View(model);
}

附注:没有必要将ProjectID的值发送到CreateDropDownListForCreateOrEdit()方法。从您现在删除的代码中,仅用于设置selectedValue属性SelectList属性,在将下拉列表绑定到属性时会忽略该属性。您只需使用public SelectList(IEnumerable items, string dataValueField, string dataTextField)

的构造函数