几周前我刚刚开始使用MVC3并且在编程阶梯中年轻,我还在学习很多东西。我最近一直在使用Models,使用TextBoxFor和其他帮助器来填充我的“Character”模型的属性。
基本上我要做的是定义一个模型然后将它传递给我的控制器,但是我在模型中定义为静态值的任何属性都在运行时作为空值传递。
以下是了解最新情况所需部分的一些片段。
Character.cs - Model
// Instances of manipulated objects.
otReal db = new otReal();
public player newPlayer = new player();
public byte[] conditions
{
get
{
return newPlayer.conditions;
}
set
{
byte[] array1 = null;
array1 = new byte[16 * 12 * 3];
newPlayer.conditions = array1;
}
}
CharacterController.cs
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Submit(Character c)
{
// Add a new character to the database via LINQ to Entities.
otReal.AddToplayers(c.newPlayer);
otReal.players.AddObject(c.newPlayer);
otReal.SaveChanges();
return View();
}
我在View中拥有的唯一帮助者是用户实际需要与之交互的帮助者。如果我进入我的控制器并在那里设置值,它们将被设置为正确的值,它将插入。任何帮助将不胜感激!
Index.cshtml - View
@using (Ajax.BeginForm("Submit", new AjaxOptions { OnComplete = "done" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>New Character Information</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name, "Character Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TownList)
</div>
<div class="editor-field">
@* @Html.DropDownList("TownList", ViewData["TownList"] as SelectList)*@
@Html.DropDownListFor(model => model.TownList, ViewData["TownList"] as SelectList)
@Html.ValidationMessageFor(model => model.TownList)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Sex)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Sex, ViewData["sex"] as SelectList)
@Html.ValidationMessageFor(model => model.Sex)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Vocation)
</div>
<div class="editor-field">
@Html.DropDownList("VocList", ViewData["VocList"] as SelectList)
@Html.ValidationMessageFor(model => model.Vocation)
</div>
<p>
<input id="button" type="submit" value="Create" />
</p>
<div style="font-family: Tahoma; font-size: large" id="completeDiv" style="display: none;">
</div>
<span></span>
</fieldset>
}
基本上我在这里要做的就是创建我的模型,它具有一堆基本值,每个'Character'将在数据库表中具有这些值。这样,当玩家创建他/她的角色时,他/她将能够输入角色名称,性别,等级(职业),起始城镇,并且所有其他值将在幕后填充并传递给控制器以进行创建。
答案 0 :(得分:3)
假设您正在尝试在'newPlayer'上设置值,那么您可以替换此
public player newPlayer = new player();
用这个
public player newPlayer { get; set; }
默认模型绑定器将在回发后的表单中创建所有内容 - 无需在模型中实例化它。
答案 1 :(得分:0)
为我的模型创建了一个构造函数,在构造函数中,我通过新实例化的玩家模型设置了默认值。温度修复,直到我读入ataddeini的解决方案。谢谢大家!