如何在MVC中将固定值插入表中

时间:2012-04-22 11:01:51

标签: asp.net-mvc asp.net-mvc-3 razor

我想在表格中插入固定日期。我怎么能这样做?

    <div class="editor-label">
        Description :
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Description, new { @class = "textboxes" })
        @Html.ValidationMessageFor(model => model.Description)
    </div>

    <div class="editor-label">
        Date :
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Date, new { @class = "textboxes" }) /// I wanna be here a fixed date .
        @Html.ValidationMessageFor(model => model.Date)
    </div>

我的控制器代码是:

public ActionResult Index(tblOrder tblorder)
        {
            if (ModelState.IsValid)
            {
                db.tblOrders.AddObject(tblorder);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet", tblorder.fxBudjet);
            ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service", tblorder.fxServiceType);
            ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate", tblorder.fxStartTime);
            return View(tblorder);
        }

我是否需要更改控制器代码?

1 个答案:

答案 0 :(得分:2)

@Html.DisplayTextFor(model => model.Date, new { @class = "textboxes" })

如果您可以在帖子中使用日期

@Html.DisplayTextFor(model => model.Date, new { @class = "textboxes" })
@Html.HiddenFor(model => model.Date)

或在post方法中,您可以使用TryUpdateModel并排除日期字段

从您的更新

编辑我将在控制器中设置模型的值,例如假设你有一个班级年,你想预先填充年份值

    public ActionResult Create()
    {
        return View(new Year() { Value = DateTime.Now.Year });
    }

再次,如果你想要它的帖子你可以使用hiddenfor或者在帖子中重新生成它

如果只在post方法中需要这个字段,那么更好的选择可能是创建一个没有该字段的viewmodel,然后在post方法中有一些映射逻辑

编辑2:与MVC音乐商店一样,你应该有2个方法来获取和发布。我会假设它是为了创造。

[HttpGet]
public ActionResult Create()
{
    ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet");
    ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service");
    ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate");
    return View(new tblOrder() { Date = DateTime.Now });
}

[HttpPost]
public ActionResult Create(tblOrder tblorder)
{
    if (ModelState.IsValid)
    {
        db.tblOrders.AddObject(tblorder);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet", tblorder.fxBudjet);
    ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service", tblorder.fxServiceType);
    ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate", tblorder.fxStartTime);
    return View(tblorder);
}

然后在你看来像

@model tblOrder

@Html.BeginForm()
{
    @Html.DisplayTextFor(model => model.Date, new { @class = "textboxes" })
    @Html.HiddenFor(model => model.Date)
    ...other form stuff
    <input type="submit" value="Delete" />
}

希望这可以让您了解如何修复代码