我在Mac中使用VSCode创建MVC。
参数" new {problem = @Model}"不应该将值从视图传递给控制器吗?
查看代码:
@model ProblemsV4.Models.ProblemModel
<h2>New Solution</h2>
@using(Html.BeginForm("SaveSolution", "Problem", new { problem = @Model }, FormMethod.Get))
{
<label>Solution: </label>
<input type="text" name="solution" /><br/><br/>
<input type="submit" value="Save"/>
}
控制器代码:
public IActionResult SaveSolution(ProblemModel problemModel, string solution)
{
SolutionModel model = new SolutionModel();
model.Solution = solution;
ProblemBC bc = new ProblemBC();
bc.AddSolution(model);
List<ProblemModel> models = bc.ListAll();
ViewBag.Message = "Solução inserida com sucesso";
return View("Index", models);
}
答案 0 :(得分:2)
您应该在控制器上收到HttpPost
,并使用HiddenFor
发送模型的参数,
HtmlHelper
没有显示任何输入。
BeginForm方法有许多签名,其中一个包含Object routeValues,它是一个包含路径参数的对象。你不需要使用它, 您可以使用其他签名:https://msdn.microsoft.com/en-us/library/dd460344(v=vs.118).aspx
第一步:
[HttpPost]
public IActionResult SaveSolution(ProblemModel problemModel, string solution)
{
SolutionModel model = new SolutionModel();
model.Solution = solution;
ProblemBC bc = new ProblemBC();
bc.AddSolution(model);
List<ProblemModel> models = bc.ListAll();
ViewBag.Message = "Solução inserida com sucesso";
return View("Index", models);
}
第二步:
@model ProblemsV4.Models.ProblemModel
<h2>New Solution</h2>
@using(Html.BeginForm("SaveSolution", "Problem", FormMethod.Post))
{
<label>Solution: </label>
<input type="text" name="solution" /><br/><br/>
@Html.HiddenFor(model => model.Problem)
@Html.HiddenFor(model => model.Description)
@Html.HiddenFor(model => model.ID)
<input type="submit" value="Save"/>
}