[英]How to assign value to input field?
我正在处理 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)
这就是 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);
}
您可以尝试的一种方法是在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.