我是ASP.NET MVC的新手。我正在做一个小项目,遇到了以下问题。
问题1: 代码 @Html.LabelFor(Model => Model.Users[i].UserName)
是不绑定数值的。
问题2.当用户点击按钮时,我想在jQuery中添加更多的行,但这些行也应该添加到列表中,并在HTTP POST中可用。 当用户点击按钮时,我想用jQuery添加更多的行,但这些行也应该被添加到列表中,并在HTTP POST中可用。
问题3:当用户点击按钮时,我想在jQuery中添加更多的行,但这些行也应该添加到列表中,并且在HTTP POST中可用。 当我点击 保存 按钮,视图模型变成 null
在 public ActionResult Index(FormCollection col, SampleViewModel viewModel)
的方法。
如何解决上述问题?
以下是完整的代码
namespace StronglyTypedModelViewDemo.Models
{
public class User
{
public string AppName { get; set; }
public string UserName { get; set; }
public string Comment { get; set; }
}
public class SampleViewModel
{
public List<User> Users { get; set; }
}
}
public class SampleController : Controller
{
// GET: Sample
public ActionResult Index()
{
SampleViewModel viewModel = new SampleViewModel();
viewModel.Users = new List<User>();
viewModel.Users.Add(new User() { UserName = "User1", AppName = "App1", Comment = "Comment1" });
viewModel.Users.Add(new User() { UserName = "User2", AppName = "App2", Comment = "Comment2" });
viewModel.Users.Add(new User() { UserName = "User3", AppName = "App3", Comment = "Comment3" });
viewModel.Users.Add(new User() { UserName = "User4", AppName = "App4", Comment = "Comment4" });
return View(viewModel);
}
[HttpPost]
public ActionResult Index(FormCollection col, SampleViewModel viewModel)
{
return View();
}
}
查看
@model StronglyTypedModelViewDemo.Models.SampleViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Index", "Sample", FormMethod.Post))
{
<div class=" form-group">
<div class="col-xs-4">
<table class="table table-condensed" id="table1">
<thead>
<tr>
<th scope="col">UserName</th>
<th scope="col">AppName</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Users.Count; i++)
{
<tr>
<td>
@Html.LabelFor(Model => Model.Users[i].UserName)
</td>
<td>
@Html.LabelFor(Model => Model.Users[i].AppName)
</td>
<td>
@Html.LabelFor(Model => Model.Users[i].Comment)
</td>
</tr>
}
</tbody>
</table>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-default" name="btn-save" id="btn-save">
<span>Add More rows by Javascript or Jquery or anyotherways</span>
</button>
</div>
<div class="form-group">
<hr class="hr-default"/>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-default" name="btn-save" id="btn-save">
<span>Save</span>
</button>
</div>
</div>
}