我有查看我在哪里创建面试问候和详细信息
这是表格
CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT IDENTITY (1, 1) NOT NULL,
[Greeting] NVARCHAR (MAX) NULL,
[Detail] NVARCHAR (MAX) NULL,
[VacancyId] INT NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE
);
以下是此视图的控制器
// Страница ввода приветствия и описания вакансии
[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
ViewBag.Teams = teams;
return View();
}
//Заносим инфу о вакансии в таблицу
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
//Int32 id = interview.Interview_Id;
//TempData["id"] = id;
return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
}
这是我的观点
@using (Html.BeginForm())
{
<div class="outer-div">
<div class="inner-div">
<div class="right-welcome-div">
<div class="right-grid-in-grid">
<div class="col-md-10">
@Html.DropDownListFor(model => model.Vacancy.VacancyId, ViewBag.Teams as SelectList, new { @class = "greeting" })
@Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })
</div>
</div>
<div class="main-left-div">
<div style="margin-left: 40px">
@Html.EditorFor(model => model.Greeting, new {htmlAttributes = new {@class = "greeting", data_bind = "textInput: Greeting", placeholder = "Приветствие", id="Greeting"}})
</div>
@Html.TextAreaFor(model => model.Detail, new { @class = "greeting2", data_bind = "textInput: Detail" })
</div>
</div>
<div class="left-welcome-div">
<div class="text-div" style="padding-top: 30px; word-break: break-all;">
<p style="font-size: 20px; margin-top: 20px; padding-left: 30px; padding-right: 40px; text-align: center;"><b><span data-bind="text: Greeting"/></b>
</p>
<p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail"/>
</p>
</div>
<div class="button-div" style="padding-top: 40px;">
<input style="float: right; margin-right: 30px; margin-top: 20px; border-radius: 12px; width: 200px;" type="submit" value="Создать" class="btn btn-default" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
function ViewModel() {
this.Greeting = ko.observable('');
this.Detail = ko.observable('');
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
}
当我点击提交按钮时,它会在Vacancies表中创建新的空行。
我不明白,为什么?
为什么会这样?
答案 0 :(得分:0)
因为您根据以下代码生成名为Vacancy.VacancyId的dropDownList,它将在Interview的属性中创建Vacancy实例,当您在dbContext中添加Interview时,EF将为Vacancy创建新行,因为interview.Vacancy不为null
@Html.DropDownListFor(model => model.Vacancy.VacancyId, ViewBag.Teams as SelectList, new { @class = "greeting" })
用此
替换代码@Html.DropDownListFor(model => model.VacancyId, ViewBag.Teams as SelectList, new { @class = "greeting" })