【问题标题】:How to assign value to input field?如何为输入字段赋值?
【发布时间】:2020-03-17 07:10:34
【问题描述】:

我正在处理 html 内容以在模型类的 mvc 视图绑定数据中显示数据,我的要求是将输入字段的值设置为来自 c# 的 html 内容。 我希望最终内容应该来自模型的 html 内容和值。 示例:

<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

这是来自文本文件的我的 html 内容。我的模型中有数据,即

public class EmployeeModel
{
    public string fname { get; set; } = "Stack"; 
    public string lname { get; set; } = "OverFlow";
}

在视图中:

@Html.Raw(ViewBag.htmlContent)

【问题讨论】:

    标签: c# html model-view-controller


    【解决方案1】:

    这就是 HtmlHelper 类的用途。

    在您的视图文件中设置视图模型并围绕它创建一个表单。

    @model Models.EmployeeModel
    
    @using (Html.BeginForm("Edit", "Employees", FormMethod.Post))
    {
        @Html.LabelFor(m => m.fname)
        @Html.TextBoxFor(m => m.fname)
        <input type="submit" value="Submit"/>
    }
    

    使用要编辑的模型实例从控制器调用视图。

    public IActionResult Edit(int id)
    {
        ...
        employee = service.GetEmployeeById(id);
    
        return View(employee);
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试的一个方法是在 Razor 中设置值:

      // your controller
      public class HomeController : Controller
          {
              [HttpGet]
              public ActionResult Index()
              {
                  return View(new EmployeeModel());// pass the actual viewmodel instance to the view here
              }
          }
      
      @model EmployeeModel
      .......
          <form action="/action_page.php">
              <label for="fname">First name:</label>
              <input type="text" id="fname" name="fname" value="@Model.fname"><br><br> <!-- reference @Model fields as usual -->
              <label for="lname">Last name:</label>
              <input type="text" id="lname" name="lname" value="@Model.lname"><br><br><!-- reference @Model fields as usual -->
              <input type="submit" value="Submit">
          </form>
      

      还有一个小提琴供你玩:https://dotnetfiddle.net/37asAw

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 2019-02-20
        • 2020-11-07
        相关资源
        最近更新 更多