我是aspnet mvc的新手,无法解决此问题:
我在带有2个提交按钮的表单中有一个“创建”视图,其中之一是标准的“保存”按钮->验证后存储数据并重定向到索引页面。 另一个保存数据,然后重定向到传递模型的同一页面,以预先填充某些表单字段的方式。 我的问题如下: 在我看来,我有一些数字输入字段,例如:
@Html.LabelFor(model => model.SpessoreMm)
@Html.TextBoxFor(model => model.SpessoreMm, new {@type="number", @min=0, @max=Int32.MaxValue, @Value=0, @class="form-control", style="margin: auto;"})
@Html.ValidationMessageFor(model => model.SpessoreMm, "", new { @class = "text-danger col-md-12" })
这是我的控制器的一部分:
if (submit == "Crea Nuovo") // this is the second button
{
_db.Scarico.Add(scarico);
_db.SaveChanges();
ViewBag.CaricoId = new SelectList(_registrationsManager.GetActiveKart(scarico.CaricoId), "Id", "Text", scarico.CaricoId);
return View(scarico); // if I set a breakpoint I see the model with correct value
}
如果我将属性@Value设置为0,则此值将覆盖从模型传递的值,如果我未设置默认值,则控制器会在尝试保存数据时给我并出现错误。
我该如何解决我的问题?
我想先将数字字段设置为0,然后再保存到控制器上,但这不是一种好方法:D
预先感谢
答案 0 :(得分:0)
我们可以遍历以下内容
查看模型和控制器操作
public class scarico
{
public int SpessoreMm { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Tut129(scarico solidoViewModel, string submit)
{
if (submit == "Crea Nuovo") // this is the second button
{
if (ModelState.IsValid)
{
//add the entity here
//_db.Scarico.Add(scarico);
//_db.SaveChanges();
}
//ViewBag.CaricoId = new SelectList(_registrationsManager.GetActiveKart(scarico.CaricoId),
// "Id", "Text", scarico.CaricoId);
return View(solidoViewModel); // if I set a breakpoint I see the model with correct value
}
//first button pushed so *save data* and redirect to index
return RedirectToAction("Index");
}
public ActionResult Tut129()
{
//Not initalizing property, so non null value type int will be zero
scarico solidoViewModel = new scarico();
return View(solidoViewModel);
}
.cshtml
@model Testy20161006.Controllers.scarico
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut129</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.SpessoreMm)
@Html.TextBoxFor(model => model.SpessoreMm,
//!!! Removing @Value = 0, and using passed value from action, if not set in action then non
//null value type int will be zero
new { @type = "number", @min = 0, @max = Int32.MaxValue, @class = "form-control", style = "margin: auto;" })
@Html.ValidationMessageFor(model => model.SpessoreMm, "", new { @class = "text-danger col-md-12" })
<input type="submit" name="submit" value="Standard Save" />
<input type="submit" name="submit" value="Crea Nuovo" />
}
</body>
</html>