如何在 httpPost 方法中使用另一个类
Posted
技术标签:
【中文标题】如何在 httpPost 方法中使用另一个类【英文标题】:How to use another class inside httpPost method 【发布时间】:2016-07-05 01:40:51 【问题描述】:在 MVC 中,我的控制器 (HomeController.cs) 我有一个使用模型 (ModelVariables) 的 httpPost actionResult 方法 (Battle),一切都很好,除非我尝试包含来自不同类 (Intermediary.cs) 的 void 方法,
我想做的:在我的 httpPost actionresult(Battle) 中正确添加任何 void 方法并正常运行,这是我的代码:
控制器(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
总结:我的代码在这里没有显示错误,但是当我运行这些值时似乎没有移动......
【问题讨论】:
【参考方案1】:ViewBag
是Controller
类的属性,在Intermediary
类中设置ViewBag
值(与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);
【讨论】:
以上是关于如何在 httpPost 方法中使用另一个类的主要内容,如果未能解决你的问题,请参考以下文章
serversocket 类如何在同一个端口上服务多个客户端连接?
idea java中Jformdesigner自动生成的类如何在public static void main(String[] args)}中引用