1
新手問:我有現有的數據繪畫到編輯屏幕..但無法讓它更新。我可以創建並列出(在其他代碼中),但在更新上做錯了什麼。我相信我在控制器中做了錯誤的事情。將按鈕操作保存到編輯屏幕中,無需更改。無法獲得數據更新
控制器代碼:
public class CompeditorController : Controller
{
private readonly BodyBuilderDB _db;
public CompeditorController(BodyBuilderDB db)
{
_db = db;
}
[HttpGet]
public ActionResult Edit(int CompeditorId)
{
var model = _db.Compeditors.Single(d => d.CompeditorId == CompeditorId);
return View(model);
}
[HttpPost]
public ActionResult Change(EditCompViewModel viewModel)
{
var compeditor = new Compeditor();
var bodybuilderDB = _db.Compeditors;
{
if (ModelState.IsValid)
compeditor.CompeditorId = viewModel.CompeditorId;
compeditor.FirstName = viewModel.FirstName;
compeditor.MiddleInt = viewModel.MiddleInt;
compeditor.LastName = viewModel.LastName;
compeditor.StreetAddress = viewModel.StreetAddress;
compeditor.City = viewModel.City;
compeditor.State = viewModel.State;
compeditor.PostalCode = viewModel.PostalCode;
compeditor.HomePhone = viewModel.HomePhone;
compeditor.CellPhone = viewModel.CellPhone;
compeditor.Height = viewModel.Height;
compeditor.Weight = viewModel.Weight;
compeditor.EmailAddress = viewModel.EmailAddress;
_db.Entry(bodybuilderDB).CurrentValues.SetValues(compeditor);
_db.SaveChanges();
}
查看代碼的結束:
<div class="editor-label">
@Html.LabelFor(model => model.Weight)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Weight)
@Html.ValidationMessageFor(model => model.Weight)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
型號:
using System;
using eManager.Core;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace eManager.Web2.Models
{
public class EditCompViewModel
{
[Key]
public int CompeditorId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string MiddleInt { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string EmailAddress { get; set; }
public string HomePhone { get; set; }
public string CellPhone { get; set; }
[Required]
public int Height { get; set; }
[Required]
public int Weight { get; set; }
}
}
謝謝!我現在會嘗試。 –
嗯,我得到了同樣的結果。數據被拖入編輯屏幕,當我修改任何值時,屏幕將重新繪製原始數據。任何其他想法? –
這裏是我做的改變:compeditor.Weight = ewModel.Weight; compeditor.EmailAddress = viewModel.EmailAddress; _db.Entry(bodybuilderDB).CurrentValues.SetValues(compeditor); _db.Entry(bodybuilderDB).State = EntityState.Modified; _db.SaveChanges(); } –