0

我想在表格中插入一个固定的日期。我怎样才能做到这一点 ?

    <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);
        }

我需要更改我的控制器代码吗?

4

1 回答 1

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 方法中需要此字段,则更好的选择可能是创建没有该字段的视图模型,然后在 post 方法中具有一些映射逻辑

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

[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" />
}

希望这能让您对如何修复代码有所了解

于 2012-04-22T11:05:12.657 回答