[英]How to assign value to input field?
Im working on html content to disply data in mvc view binding data from model class, my requirement is to set values to input fields to html content from c#.我正在处理 html 内容以显示来自模型类的 mvc 视图绑定数据中的数据,我的要求是将输入字段的值设置为来自 c# 的 html 内容。 i want final content should come up with html content and values from model.我希望最终内容应该包含模型中的 html 内容和值。 EXAMPLE:例子:
<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>
This is my html content which is coming from text file.这是我的 html 内容,它来自文本文件。 i've data in my model, ie,我的模型中有数据,即
public class EmployeeModel
{
public string fname { get; set; } = "Stack";
public string lname { get; set; } = "OverFlow";
}
In View :在视图中:
@Html.Raw(ViewBag.htmlContent)
This is what the HtmlHelper class is for.这就是 HtmlHelper 类的用途。
Set the view model in your view file and create a form around it.在您的视图文件中设置视图模型并围绕它创建一个表单。
@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"/>
}
Invoke the view from your controller with an instance of the model to edit.使用要编辑的模型实例从控制器调用视图。
public IActionResult Edit(int id)
{
...
employee = service.GetEmployeeById(id);
return View(employee);
}
one thig you could try would be to set values in Razor:您可以尝试的一种方法是在 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>
and a fiddle for you to play with: https://dotnetfiddle.net/37asAw和一个供你玩的小提琴: https : //dotnetfiddle.net/37asAw
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.