我需要一个控制器,单击按钮后将在模型var1中存储1或2的值(取决于选择了哪个单选按钮),在var2上存储3或4的值(取决于从列表中选择的选项)然后计算var3(var1 + var2)并将其写在“结果”列的原始数据上。
这是代码:
型号(Class1)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test1.Models
{
public class Class1
{
public int var1 { get; set; }
public int var2 { get; set; }
public int var3 { get; set; }
}
}
控制器(HomeController)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test1.Controllers
{
public class HomeController : Controller
{
public ActionResult Page()
{
return View();
}
}
}
查看(页)
@model Test1.Models.Class1
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Page</title>
</head>
<body>
<div>
@using (Html.BeginForm("Page", "Class1", FormMethod.Post)) //should I use this without the FormMethod.Post?
{
<table style="width:100%" align="center" cellpadding="10">
<tr>
<th>1</th>
<th>2</th>
<th>var2</th>
<th>Result</th>
</tr>
<tr>
<td> @Html.RadioButtonFor(m => m.var1, "1") </td>
<td> @Html.RadioButtonFor(m => m.var1, "2") </td>
<td> @Html.DropDownListFor(m => m.var2, new List<SelectListItem>
{new SelectListItem{Text="3", Value="3"},
new SelectListItem{Text="4", Value="4"}})
</td>
<td></td>
</tr>
</table>
}
<input id="Button1" type="button" value="button"/>
</div>
</body>
</html>
最佳答案
您应该使用输入的View:
@model Simulador;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div>
@using (Html.BeginForm("Simular", "Simulador", FormMethod.Post))
{
<table>
<td align="left"> Result</td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "5") </td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "4") </td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "3") </td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "2") </td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "1") </td>
<td align="center"> @Html.RadioButtonFor(m => m.Var1, "0") </td>
<td align="center">
@Html.DropDownListFor(m => m.Var2, new List<SelectListItem>
{new SelectListItem{Text="low", Value="1"},
new SelectListItem{Text="medium", Value="2"},
new SelectListItem{Text="high", Value="3"},
new SelectListItem{Text="very high", Value="4"}}
</td>
<p id="var"></p>
<input type="submit" value="Submit" onclick="givevar3()" />
}
</div>
</body>
</html>
然后尝试在
return View();
函数中返回模型[HttpPost]
public ActionResult Simular(Simulador simulador)
{
int var1 = simulador.Var1;
int var2 = simulador.Var2;
int var3 = simulador.Var3 = (simulador.Var2 + simulador.Var1) *5;
return View(simulador);
}
关于asp.net-mvc - MVC Controller 来存储和显示变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56751182/