C# 模型在Html.BeginForm之外为Null
堆栈中有许多类似的问题,但没有一个完全解决我的问题 我有一个具有各种属性的模型,其中一个是列表:C# 模型在Html.BeginForm之外为Null,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,堆栈中有许多类似的问题,但没有一个完全解决我的问题 我有一个具有各种属性的模型,其中一个是列表: public class MyModel { .... public List<ValuesViewModel>Values { get; set; } } 我成功地使用下拉列表在我的视图中输出它们,以修改如下值: @using (Html.BeginForm("GenerateReport", "Job", method: FormMethod.Post)) {
public class MyModel
{
....
public List<ValuesViewModel>Values { get; set; }
}
我成功地使用下拉列表在我的视图中输出它们,以修改如下值:
@using (Html.BeginForm("GenerateReport", "Job", method: FormMethod.Post))
{
<div class="container">
@{
List<SelectListItem> statuses = new List<SelectListItem>();
statuses.Add(new SelectListItem
{
Text = "Bad",
Value = "Bad"
});
statuses.Add(new SelectListItem
{
Text = "Fair",
Value = "Fair",
Selected = true
});
statuses.Add(new SelectListItem
{
Text = "Good",
Value = "Good"
});
for (int i = 0; i < Model.Values.Count; ++i)
{
@Html.EditorFor(model => Model.Values[i].Name)
<p>Status One @Html.DropDownListFor(model => Model.Values[i].StatusOne, Values )</p>
<p>Status Two @Html.DropDownListFor(model => Model.Values[i].StatusTwo, Values )</p>
}
}
</div>
<button type="submit" class="btn btn-custom saveButtons ">Create report</button>
}
在@HTML.BeginForm
之外,我的控制器方法中的模型将完全为空,即:
public ActionResult GenerateReport(MyModel model)
{
// model is null here!
}
public ActionResult GenerateShortReport(MyModel model)
{
// model is null here!
}
这里最愚蠢的解决方案是为每个按钮使用BeginForm
,但我希望并相信还有另一种方法。
如何将列表值解析为多个控制器方法,而不为每个按钮复制整个dropdownlist 您可以使用单个
中
元素的formaction
属性提交给不同的控制器方法(该属性覆盖表单的action属性)
在控制器中
public ActionResult GenerateReport(MyModel model, string action)
{
if (action == "Create report")
{
.... // code to generate standard report
}
else
{
.... // code to generate short version
}
你试过
[HttpPost]
和[FromBody]
属性吗?@StephenMuecke这正是我需要的,现在它工作得很好!非常感谢。它在web中非常复杂。formaction工作正常,但是,我尝试传递另一个属性,它又是一个默认值……我刚刚在for循环之前添加了:@Html.HiddenFor(model=>model.JobId)
,但它不工作,怎么了?JobId是“MyModel”中与此问题无关的属性,因此您需要提出一个新问题。但您需要提供更多信息,包括代码,包括显示如何/在何处设置属性值
public ActionResult GenerateReport(MyModel model)
{
// model is null here!
}
public ActionResult GenerateShortReport(MyModel model)
{
// model is null here!
}
<button type="submit" formaction="@Url.Action("GenerateReport", "Job")">Create report</button>
<button type="submit" formaction="@Url.Action("GenerateShortReport", "Job")">Create short report</button>
<input type="submit" name="action" value="Create report" />
<input type="submit" name="action" value="Create short report" />
public ActionResult GenerateReport(MyModel model, string action)
{
if (action == "Create report")
{
.... // code to generate standard report
}
else
{
.... // code to generate short version
}