我正在创建一个MVC应用程序,我想在视图之间传递数据 这是我的第一个观点:
@model ClassDeclarationsThsesis.Models.AddGroupViewModel
@{
ViewBag.Title = "Add Groups";
}
<h2>Add Groups to subjects</h2>
@foreach (var user in Model.Users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("AddGroup", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create new groups.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@{
List<SelectListItem> listItems1 = new List<SelectListItem>();
}
@foreach (var subject in Model.Subjects)
{
listItems1.Add(new SelectListItem
{
Text = subject.name,
Value = subject.name,
Selected = true
});
}
@Html.LabelFor(m => m.subject_name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.subject_name, listItems1, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.qty, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.qty, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
我的控制器:
public ActionResult AddGroup(AddGroupViewModel model)
{
var entities = new ClassDeclarationsDBEntities1();
var model1 = new AddGroupViewModel();
model1.Subjects = entities.Subjects.ToList();
model1.Users = entities.Users.ToList();
// set your other properties too?
if (ModelState.IsValid)
{
return RedirectToAction("AddGroupsQty", "Account");
}
return View(model1);
}
我想要实现的是将所选项目从下拉列表和此qty变量传递到AddGroupsQty View。我该怎么做呢?在我的AddGroupsQty控制器中,我到目前为止只有一个简单的视图返回。
答案 0 :(得分:1)
您可以使用querystring传递值。
return RedirectToAction("AddGroupsQty", "Account",
new { qty=model.qty,subject=model.subject_name);
假设您的AddGroupsQty
有两个参数来接受数量和主题
public ActionResult AddGroupsQty(int qty,string subject)
{
// do something with the parameter
// to do : return something
}
这将使浏览器使用查询字符串中的值发出新的GET请求。如果您不喜欢这样做,您可以使用服务器端临时持久性mecahnism,如TempData
TempData["qty"]=model.qty;
TempData["subject"]= model.subject_name;
return RedirectToAction("AddGroupsQty", "Account");
在您的AddGroupsQty
行动中,
public ActionResult AddGroupsQty()
{
int qty=0;
string subjectName=string.Empty;
if(TempData["qty"]!=null)
{
qty = Convert.ToInt32(TempData["qty"]);
}
if(TempData["subject"]!=null)
{
subjectName = TempData["subject"];
}
// Use this as needed
return View();
}
如果要将这些值从ADdGroupsQty操作传递到它的视图,可以使用视图模型或ViewBag / ViewData。