Case是一个MVC 5应用程序
我有一个班级(运动队),看起来像这样:
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
public string Badge { get; set; }
public TeamColor? TeamColor { get; set; }
public League? League { get; set; }
public bool HasAlias { get; set; }
public bool IsAlias { get; set; }
public int? AliasId { get; set; }
public virtual Team AliasTeam { get; set; }
public virtual ICollection<Team> Aliases { get; set; }
}
AliasTeam是一个只有TeamName和AliasId的团队。
如果用户单击原始团队中的HasAlias复选框,如何添加用于归档AliasTeamName的文本框?如何在控制器中循环文本框以将其添加为具有AliasId的团队原来的团队?
控制器操作现在看起来像这样,我可以添加一个团队
public ActionResult CreateTeam(CreateTeamViewModel model)
{
if (ModelState.IsValid)
{
var team = new Team
{
TeamName = model.TeamName,
TeamColor = model.TeamColor,
League = model.League
};
db.Teams.Add(team);
db.SaveChanges();
return RedirectToAction("AddTeamImage", new {teamid = team.Id});
}
return View(model);
}
编辑:
通过添加以下js来解决它:
$(document).ready(function() {
$("#HasAlias").change(function () {
if (this.checked) {
$(".textboxes").append('<div><input class="form-control text-box single-line" placeholder="enter aliasname" type="text" name="teams"/><a href="#" class="add_field"> <span class=" glyphicon glyphicon-plus-sign"></span></a><a href="#" class="remove_field"> <span class=" glyphicon glyphicon-minus-sign"></span></a></div>');
} else {
$(".textboxes").empty();
}
});
$('.textboxes').on("click", ".add_field", function(e) {
e.preventDefault();
$(".textboxes").append('<div><input class="form-control text-box single-line" placeholder="enter aliasname" type="text" name="teams"/><a href="#" class="add_field"> <span class=" glyphicon glyphicon-plus-sign"></span></a><a href="#" class="remove_field"> <span class=" glyphicon glyphicon-minus-sign"></span></a></div>');
});
$('.textboxes').on("click", ".remove_field", function (e) {
e.preventDefault(); $(this).parent('div').remove();
});
});
然后在Action中循环遍历各个团队:
public ActionResult CreateTeam(CreateTeamViewModel model, string[] teams)
{
if (ModelState.IsValid)
{
var team = new Team
{
TeamName = model.TeamName,
TeamColor = model.TeamColor,
League = model.League,
HasAlias = model.HasAlias
};
db.Teams.Add(team);
db.SaveChanges();
foreach (var s in teams)
{
var t = new Team
{
TeamName = s,
AliasId = team.Id,
IsAlias = true
};
db.Teams.Add(t);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(model);
}
我可能误解了整个ViewModel范例。我认为你创建ViewModel的意义在于,只需要创建结果所需的信息。