如何在Html.TextBoxFor()中显示可由用户编辑的默认值?

时间:2012-07-24 19:11:01

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

我正在使用TextBoxFor来显示可编辑字段。我需要此字段显示值“150”,但允许更改值。

我尝试过使用@Html.TextBoxFor(m => m.MembershipDues, new { @Value = "150" }),但这不适合我。

以下是我的模型字段:

[Required]
    [DataType(DataType.Text)]
    public decimal MonthlyPayment { get; set; }

    [Required]
    [DataType(DataType.Text)]
    public decimal MaintenanceFees { get; set; }

    [Required]
    [DataType(DataType.Text)]
    public decimal MembershipDues { get; set; }

    [Required]
    [DataType(DataType.Text)]
    public decimal ExchangeFees { get; set; }

    [Required]
    public string Duration { get; set; }

    public decimal AnnualPayment { get; set; }
    public decimal AnnualMaintenance { get; set; }
    public decimal AnnualTotal { get; set; }
    public decimal TenYearPayment { get; set; }
    public decimal TenYearMaintenancePercentage { get; set; }
    public decimal TenYearMembershipAndExchange { get; set; }
    public decimal TenYearTotal { get; set; }
    public decimal AnnualVacationCost { get; set; }

这是我的行动

        [OutputCache(Duration = 60)]
    public ActionResult CalculationView()
    {         
        return View();
    }

    [HttpPost]
    [OutputCache(Duration = 60)]
    public ActionResult Index(CalculaterModel cm)
    {
        if (ModelState.IsValid)
        {
            if (cm.Duration == "Annual")
                cm.AnnualMaintenance = cm.CalculateMaintenanceFeesAnnually(cm.MaintenanceFees);
            else if (cm.Duration == "Monthly")
                cm.AnnualMaintenance = cm.CalculateMaintenanceFeesMonthly(cm.MaintenanceFees);

            cm.AnnualPayment = cm.MonthlyPayment * 12;
            cm.AnnualTotal = cm.AnnualPayment + cm.AnnualMaintenance;
            cm.TenYearPayment = cm.AnnualPayment * 10;

            decimal percentage = .08m;
            decimal cost;
            int i = 1;
            decimal rate = cm.AnnualMaintenance;
            while (i <= 10)
            {
                cost = rate * percentage;
                rate = cost + rate;
                cm.TenYearMaintenancePercentage = cm.TenYearMaintenancePercentage + rate;
                i++;
            }
            decimal MDF = cm.MembershipDues + cm.ExchangeFees;
            cm.TenYearMembershipAndExchange = MDF * 10;
            cm.TenYearTotal = cm.TenYearMembershipAndExchange + cm.TenYearMaintenancePercentage + cm.TenYearPayment;
            cm.AnnualVacationCost = cm.TenYearTotal / 10;
            return View(cm);
        }
        return View();
    }

我的文本框需要显示“150”并且可以编辑。 任何帮助将不胜感激。提前谢谢!

1 个答案:

答案 0 :(得分:2)

有一个令人困惑的问题是,如果您没有使用视图指定模型,即使使用Razor语法设置了默认值,也不会设置默认值。

更改

return View();

var cm = new CalculaterModel();
return View(cm);

看看是否有效。