目前我正在使用ViewData和Viewbag存储数据和tempdata进行重定向,所有这些工作正常。
我只是想知道在MVC回发期间是否有任何优化方式来存储数据或控制值?
这是我的控制器方法,我将两个模型类从控制器传递给使用动态对象的视图。
[HttpGet]
public ActionResult Index(int? page)
{
IList<Customer> _CustomerList = new List<Customer>();
IList<LCOddl> LCODDL= new List<LCOddl>();
// some logic to bind both classed with database ..
dynamic DashboardClassed = new ExpandoObject();
DashboardClassed.LCODDL = LCODDL;
DashboardClassed.CUSTOMER = _CustomerList.ToPagedList(page ?? 1, 30);
return View(DashboardClassed);
}
这是我的剃刀视图,它使用动态对象:
@using PagedList;
@using PagedList.Mvc;
@model dynamic
@{
Layout = null;
}
@using (Html.BeginForm("SearchMethod", "Dashboard", FormMethod.Post))
{
@foreach (Models.LCOddl item in Model.LCODDL)
{
// Render HTML
}
@foreach (Models.Customer item in Model._CustomerList )
{
// render html
}
<div class="form-group"><button type="submit" class="btn btn-success">Go</button></div>
}
从我的剃刀视图点击按钮后,将调用Dashboard Controller中的SearchMethod。
现在我想要两件事:
如果我使用tempdata存储数据,或者还有其他优化方法可以做同样的话,我的问题也是一样的。
答案 0 :(得分:1)
在回发期间保留表单值的最佳方法是将您的视图绑定到view model
。
我写了一个关于视图模型的答案,请去阅读:
让我们一步一步地完成它。我不知道你想要实现什么,所以我将使用我自己的例子。我们假设您正在尝试添加新用户。
首先为表单数据创建视图模型。您的视图模型与您的域模型不同,因为它只包含您要在视图上使用的数据。有时您的域模型可能包含大量数据,但您不想添加或编辑所有内容。因此,您只创建一个视图模型,其中只包含您要添加或编辑的数据。在我们的示例中,我只想为我的用户添加名字和姓氏,因此我将创建2个属性,即FirstName
和LastName
:
public class UserViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
上面的视图模型将被实例化,并从您的action方法传递给视图。发布表单后,您的操作方法将接收此视图模型作为参数。它将包含名字和姓氏的值(如果输入):
public class UserController : Controller
{
private IUserRepository userRepository;
public UserController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
public ActionResult Create()
{
UserViewModel model = new UserViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(UserViewModel model)
{
// Do some form validation
if (!ModelState.IsValid)
{
return View(model);
}
// If form validation succeeds do what you need to do
}
}
在您的创建视图中,它将接收此视图模型。您需要做的就是创建一个包含2个文本框的表单,其中包含名字和姓氏以及提交按钮:
@model YourProjectName.ViewModels.UserViewModel
@using (Html.BeginForm())
{
<div>
@Html.TextBoxFor(m => m.FirstName, new { maxlength = "50" })
@Html.ValidationMessageFor(m => m.FirstName)
</div>
<div>
@Html.TextBoxFor(m => m.LastName, new { maxlength = "50" })
@Html.ValidationMessageFor(m => m.LastName)
</div>
<div>
<button type="submit">Save</button>
</div>
}
这是一个基本的例子。通过它,玩弄代码,以便您可以在您的场景中实现它。