我正在尝试创建一个MVC站点,并且我对ViewBag有了一些了解。
就像它不能包含元素一样。
我正在使用MVC 4。
这是我在控制器中的功能:
public ActionResult Create()
{
ViewBag.DiscID = new SelectList(entities.Disc, "ID", "ID");
ViewBag.StarID = new SelectList(entities.Star, "ID", "Name");
ViewBag.Num = 7;
return View();
}这是我的创作视图:
@model Movies.Models.StarAndRole
@{
ViewBag.Title = "Create";
int num;
int.TryParse(ViewBag.Num, out num);
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>StarAndRole</h4>
<h3>num is = @num</h3>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.StarID, "Star", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("StarID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.StarID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DiscID, "Disc Num", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DiscID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DiscID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}在我看来,我在ViewBag中放入的所有内容都是空的。
我做错什么了?
提前谢谢你!
发布于 2016-02-02 19:58:34
Int.TryParse方法接受字符串( int值的表示)。但是,您将动态类型传递给该方法。这应该会给你一个错误。
如果您知道您正在从操作方法中设置Int值,则在您的视图中,您可以简单地读取它如下
int num = ViewBag.Num;更好的解决方案是将要传递给视图的数据添加到视图模型中。
public class YourCreateVm
{
public string Description { set;get;}
public int Num { set;get;}
public List<SelectListItem> Disks { set;get;}
public int SelectedDiskId { set;get;}
}在你的视野中
public ActionResult Create()
{
var vm = new YourCreateVm { Num = 7 };
vm.Disks = entities.Disc.Select(s=> new SelectListItem
{ Value=s.ID.ToString(), Text =s.Name}).ToList();
return View(vm);
}在你看来
@model YourCreateVm
@using(Html.BeginForm())
{
<p>My num is : @Model.Num <p>
@Html.TextBoxFor(s=>s.Description)
@Html.DropDownListFor(s=>s.SelectedDiskId, Model.Disks)
<input type="submit" />
}https://stackoverflow.com/questions/35162162
复制相似问题