在MVC中我的控制器(HomeController.cs)我有一个使用模型(ModelVariables)的httpPost actionResult方法(Battle),一切都很好,除非我尝试从不同的类(Intermediary.cs)中包含一个void方法,
我想做什么:在我的httpPost actionresult(Battle)中正确添加任何void方法并正确运行,这是我的代码:
Controller(HomeController.cs):
[HttpGet]
public ActionResult Index()
{
ModelVariables model = new ModelVariables()
{
CheckBoxItems = Repository.CBFetchItems(),
CheckBoxItemsMasteries = Repository.CBMasteriesFetchItems(),
CheckBoxItemsLevel = Repository.CBLevelFetchItems(),
CheckBoxItemsItems = Repository.CBItemsFetchItems(),
CheckBoxItemsFioraSLevel = Repository.CBFioraSLevelFetchItems(),
CheckBoxItemsRunes = Repository.CBRunesFetchItems(),
Inter = new Intermediary() //Here I instantiate other class
};
return View("Index", model);
}
[HttpPost]
public ActionResult Battle(ModelVariables model)
{
Inter.InstantiateRunes(model); //hmm doesent seem to work
return View("Battle", model);
}
其他课程(Intermediary.cs):
public void InstantiateRunes(ModelVariables model)
{
var LifeStealQuintCount = model.CheckBoxItemsRunes.Where(x => x.CBIsSelectedRunes).Select(x => x.CBRunesID = "LS").ToList().Count;
var LifeStealQuintValue = model.CheckBoxItemsRunes.Where(x => x.CBIsSelectedRunes && x.CBRunesID == "LS").Select(x => x.CBRunesValue).FirstOrDefault();
if (model.CheckBoxItemsRunes != null && LifeStealQuintCount != 0 && LifeStealQuintValue != 0)
{
ViewBag.runeTest = LifeStealQuintValue * LifeStealQuintCount; //I set the values here, what's wrong?
}
}
查看(Battle.cshtml):
@ViewBag.runeTest //unable to display due to void method not working
总结:我的代码在这里没有显示任何错误,但是当我运行这些值时似乎没有错误......
答案 0 :(得分:1)
ViewBag
是Controller
类的属性,在ViewBag
类中设置Intermediary
值(与Controller
无关)将无效
您尚未指出LifeStealQuintValue
的类型,但假设其int
(LifeStealQuintCount
为)且乘法结果将始终为int
,然后将您的方法更改为
public int? InstantiateRunes(ModelVariables model)
{
var LifeStealQuintCount = model.CheckBoxItemsRunes.Where(x => x.CBIsSelectedRunes).Select(x => x.CBRunesID = "LS").ToList().Count;
var LifeStealQuintValue = model.CheckBoxItemsRunes.Where(x => x.CBIsSelectedRunes && x.CBRunesID == "LS").Select(x => x.CBRunesValue).FirstOrDefault();
if (model.CheckBoxItemsRunes != null && LifeStealQuintCount != 0 && LifeStealQuintValue != 0)
{
return LifeStealQuintValue * LifeStealQuintCount; //I set the values here, what's wrong?
}
return null;
}
然后将POST方法更改为
[HttpPost]
public ActionResult Battle(ModelVariables model)
{
ViewBag.runeTest = Inter.InstantiateRunes(model);
return View("Battle", model);
}