【问题标题】:MVC4 cshtml page function callMVC4 cshtml页面函数调用
【发布时间】:2016-07-22 17:52:46
【问题描述】:

当它第一次加载时,我需要在我的 mvc 页面上的可编辑文本框中显示一个值(如果存在)。我有一个函数可以获取我需要的值,但是我需要从当前模型中传递参数以从数据库中获取我需要的值。 我遇到的问题是将这个值放入文本框中。我尝试的是

cshtml:

@Html.TextBoxFor(model => model.AdjustedLiabilityAmount, new { @Value=OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount))}

我得到一个红色波浪线“当前上下文中不存在名称'Value'”

所以我尝试了一种我读到的不同的技术,就像这样。

控制器:

public ActionResult Index()
    {
        ViewBag.AdjustedValue = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount);

cshtml:

@Html.TextBoxFor(model => model.AdjustedLiabilityAmount, new { @Value=ViewBag.AdjustedValue)}

这次我得到了红色的波浪状“名称'模型'在当前上下文中不存在。”

我确定我只是缺少一些基本的东西,因为我是 MVC 的新手。

非常感谢任何帮助。

整个 ActionResult 索引:

public ActionResult Index()
    {
        ViewBag.AdjustedValue = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetLatestAdjustedLiabilityAmount(Model.DOTNumber, Model.LiabilityAmount);
        var Report = new OBS_LIB.DTO.JeopardyAssessmentReport();
        Report.Stage = 1;
        Report.Status = "Active";
        Report.ReportItems = OBS_LIB.BLL.JeopardyAssessment.JeopardyAssessment.GetJAReportItems(Report.Stage, Report.Status);
        return View(Report);
    }

【问题讨论】:

  • 为什么要使用@Value 而不是Value? Razor 通常将其检测为“写入输出”,而不是让 C# 代码将其用作特殊名称的转义值...(另外,Value 不是特殊名称 - 使用 @Value 对我来说毫无意义)跨度>

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


【解决方案1】:

你想做这样的事情:

类:

public class ModelClassHere {
     public float Liability {get;set;}
}

控制器:

public ActionResult Index(ModelClassHere model) {
    model.Liability = 10.00;
    return View(model); // pass model to the view
}

查看:

@Html.TextBoxFor(x => x.Liability) // 'x' can be anything

编辑*

如果你已经有一个模型并且需要传递一个简单的值:

控制器:

public ActionResult Index(ModelClassHere model, string otherValue) {
    model.Liability = 10.00;
    ViewBag.Liability = model.Liability;
    return View(model); // pass model to the view
}

查看:

<input type="text" id="otherValue" name="otherValue" value="@ViewBag.Liability.ToString()" />

【讨论】:

  • 问题是 ActionResult 索引已经返回了一些东西。在上面的问题中添加了整个方法。
  • 最好的办法是将您的字段添加到您的报告模型中。但是请参阅我所做的编辑,这是我能想到的唯一其他方式,特别是如果您计划在编辑后将数据传回控制器。 @克里斯
【解决方案2】:

你可以使用 @Html.TextBox("AdjustedLiabilityAmount", (Decimal)ViewBag.AdjustedValue)}

或者

@Html.TextBox("AdjustedLiabilityAmount", Model.AdjustedLiabilityAmount == null ? (Decimal)ViewBag.AdjustedValue : Model.AdjustedLiabilityAmount)}

在十进制类型中,您输入您需要的类型。

【讨论】:

    【解决方案3】:

    您需要在 控制器

        return view(myModelName);
    

    确保您可以在控制器中访问它。

    您的视图也必须引用顶部@model 行中的模型。

    终于要调用模型了

    查看:

        Model.myModelName
    

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      相关资源
      最近更新 更多