我有这样的模特
public class TutorialModel
{
public string TitleWord { get; set; }
public List<string> PossibleAnswers { get; set; }
public List<bool> Colors { get; set; }
}
和控制器
public class TutorialController : Controller
{
//
// GET: /Tutorial/
private TutorialModel model = new TutorialModel();
public ActionResult Index(TutorialModel paramModel)
{
model.TitleWord = "Go";
model.Colors = new List<bool>();
model.PossibleAnswers = new List<string>();
model.PossibleAnswers.Add("1");
model.PossibleAnswers.Add("2");
model.PossibleAnswers.Add("3");
model.PossibleAnswers.Add("4");
return View(this.model);
}
public ActionResult PressButton(int? id)
{
if (model.TitleWord == model.PossibleAnswers[(int) id])
{
model.Colors[(int) id] = true;
}
return RedirectToAction("Index", model);
}
}
带视图的
@{
ViewBag.Title = "Tutorial";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<button type="button" class="btn btn-default">@Model.TitleWord</button>
<br/>
@{
var textColor = "green";
}
<div class="btn-group">
@for (int i = 0; i < Model.PossibleAnswers.Count; i++)
{
<button type="button" class="btn btn-default" style="color: @textColor" onclick = " window.location.href = '@Url.Action("PressButton", "Tutorial", new {id = i})' ">@Model.PossibleAnswers[i]</button>
}
</div>
按下其中一个按钮后,我需要获取我在视图中使用的模型和按下的按钮。关于我得到的按钮的信息,但我不知道如何从视图到控制器获取信息发送模型。请帮我解决这个问题。
答案 0 :(得分:0)
您必须添加一个表单元素,并且您要发送回服务器的所有值都应放在输入元素中,如果您不想在文本字段中显示它,可以使用隐藏字段。 / p>
答案 1 :(得分:0)
在视图中:
@using (Html.BeginForm())
{
@{
ViewBag.Title = "Tutorial";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<button type="button" class="btn btn-default">@Model.TitleWord</button>
<br/>
@{
var textColor = "green";
}
<div class="btn-group">
@for (int i = 0; i < Model.PossibleAnswers.Count; i++)
{
<button type="button" name="btn" class="btn btn-default" style="color: @textColor" onclick = " window.location.href = '@Url.Action("PressButton", "Tutorial", new {id = i})' ">@Model.PossibleAnswers[i]</button>
}
</div>
}
在控制器中,您可以使用FormCollection获取值,并可以从中提取值,如:
public ActionResult PressButton(FormCollection collection)
{
string s=collection["btn"]; //string parameter passed is the name of the field defined in the view to a control.(btn is the name for the Button)
}