我正在尝试使用MVC将数据插入数据库(SQL)。 首先,我从存储在SQL中的表中获取数据到MVC中。然后加入他们。
SQL
SELECT articleId, articleName, price, supply FROM Article;
SELECT customerId, customerName, city, state FROM Customer;
型号
namespace Articles.Models
{
public class Class
{
public int articleId { get; set; }
public Nullable<int> articleName { get; set; }
public string customerId { get; set; }
public string customerName { get; set; }
}
}
控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Articles.Models;
namespace My_App.Controllers
{
public class ArticlesController : Controller
{
[HttpPost]
public ActionResult Articles()
{
Data db = new Data();
List<Class> ClassList = new List<Class>();
var together = (from a in db.Article
join c in db.Customer on a.articleId equals c.articleId
select new { a.articleId, a.articleName, c.customerId, c.customerName }).ToList();
foreach (var item in together)
{
Class cl = new Class();
cl.articleId = item.articleId;
cl.articleName = item.articleName;
cl.customerId = item.customerId;
cl.customerName = item.customerName;
ClassList.Add(cl);
}
return View(ClassList);
}
查看
@model IEnumerable<Article.Models.Class>
@using (Html.BeginForm("Article, "Article", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-horizontal">
@Html.ValidationSummary(true)
@foreach (var item in Model)
{
<div class="form-group">
@Html.LabelFor(modelItem => item.articleId , new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(modelItem => item.articleId)
@Html.ValidationMessageFor(modelItem => item.articleId )
</div>
</div>
<div class="form-group">
@Html.LabelFor(modelItem => item.articleName , new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(modelItem => item.articleName )
@Html.ValidationMessageFor(modelItem => item.articleName )
</div>
</div>
<div class="form-group">
@Html.LabelFor(modelItem => item.customerId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(modelItem => item.customerId)
@Html.ValidationMessageFor(modelItem => item.customerId)
</div>
</div>
<div class="form-group">
@Html.LabelFor(modelItem => item.customerName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(modelItem => item.customerName)
@Html.ValidationMessageFor(modelItem => item.customerName)
</div>
</div>
}
我的问题是,如何将View中的输入数据插入数据库。我认为我的模型(类)中的数据应该存储在数据库中。但是我不知道该怎么做。还是视图中有错误的呼叫?
Thx, 小猫咪