我的MVC網站存在一些問題,數據庫特別保存。所以基本上,我已經創建了一個頁面,您可以在其中添加一個新的類別到數據庫。但是當它使用WCF Web服務的函數時,它似乎保存瞭解決方案名稱,而不是在「創建」表單中輸入的字符串。使用Create時項目名稱保存到數據庫而不是字符串
的服務功能:
public string addCategory(string Name)
{
Database1Entities1 tbl = new Database1Entities1();
Category newCtg = new Category() {
Namn = Name,
};
tbl.Category.Add(newCtg);
try
{
tbl.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
string msg = "Done";
return msg;
}
控制器:
public class CategoryController : Controller
{
//
// GET: /Category/
localhost.Service1 srvc = new localhost.Service1();
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Category newCtg)
{
if (ModelState.IsValid)
{
srvc.addCategory(newCtg.ToString());
return RedirectToAction("Index");
}
else
{
return View();
}
}
}
而且CSHTML文件:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Category</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Namn, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Namn)
@Html.ValidationMessageFor(model => model.Namn)
</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>
DB的截圖:
您使用的數據層是什麼?實體框架?請用適當的標籤[編輯]你的問題。 –