2016-10-05 12 views
0

を使用してSQL Server 2014にデータを挿入することができません、私はにデータを追加していない、次のリンクのチュートリアル私は.NETの全く新しいですAsp.net MVC4

https://www.youtube.com/watch?v=WLD6DvLI35Y&list=PLx7nFxMa-ZcIz2VBKC8FyMjQNmlIvrAi9

が、第2のビデオのように従ってみましたデータベース。私はバグを見つけることができません。 私はここでVSエクスプレス2012、ASP.NET MVC4およびSQL Serverに2014

を使用しています私のコードです:

Index.cshtml

@model MyApp.Models.StudentModel 

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Hi @ViewBag.message</h2> 
@using (Html.BeginForm("SaveDataStudent", "Student", new { @id = "Form" }, FormMethod.Post)) 
{ 
@Html.ValidationSummary(); 
@Html.AntiForgeryToken();` 

@Html.LabelFor(m=>m.productname) 
@Html.TextAreaFor(m=>m.productname) 
@Html.ValidationMessageFor(m => m.productname) 

@Html.LabelFor(m=>m.quantity) 
@Html.TextAreaFor(m=>m.quantity) 
@Html.ValidationMessageFor(m => m.quantity) 

@Html.LabelFor(m=>m.price) 
@Html.TextAreaFor(m=>m.price) 
@Html.ValidationMessageFor(m => m.price) 

<input type="submit" value ="Save" name ="Save" /> 

} 
@section Scripts{ 
    @Scripts.Render("~/bundles/jqueryval") 

} 

StudentCotroller

using MyApp.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MyApp.Controllers 
{ 
    public class StudentController : Controller 
    { 
     // GET: /Student/ 
     protected CodeDB d = new CodeDB(); 

     public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult SaveDataStudent(StudentModel f) 
     { 
      if (ModelState.IsValid) 
      { 
       d.Open(); 
       int i = d.DataInsert("INSERT INTO tblproduct(productname,price,quantity)VALUES('" + f.productname + "','" + f.price + "','" + f.quantity + "')"); 

       //here getting i=0 
       if (i > 0) 
       { 
         ModelState.AddModelError("Success", "Save Success"); 
       } 
       else 
       { 
        ModelState.AddModelError("Error", "Save Error"); 
       } 

       d.Close(); 
      } 
      else 
      { 
       var errors = ModelState.Values.SelectMany(v => v.Errors); 
      } 

      return View("Index"); 
     } 
    } 
} 

CodeDB。 cs

using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 
using System.Web.Configuration;` 

namespace MyApp.Models 
{ 
    public class CodeDB 
    { 
     protected SqlConnection con;` 

     public bool Open(string Connection = "DefaultConnection") 
     { 
      con = new  SqlConnection(@WebConfigurationManager.ConnectionStrings[Connection].ToString()); 

      try 
      { 
       bool b = true; 

       if (con.State.ToString() != "Open") 
       { 
        con.Open(); 
       } 

       return b; 
      } 
      catch (SqlException ex) 
      { 
       return false; 
      } 
     } 
     //end Open Connection 

     //close connection 
     public bool Close() 
     { 
      try 
      { 
       con.Close(); 
       return true; 
      } 
      catch (Exception ex) 
      { 
       return false; 
      } 
     } 

     public int ToInt(Object s) 
     { 
      try 
      { 
       return Int32.Parse(s.ToString()); 
      } 
      catch 
      { 
       return 0; 
      } 
     } 

     //Insert Data 
     public int DataInsert(String sql) 
     { 
      int lastID = 0; 
      String query = sql + ";[email protected]@Identity;"; 

      try 
      { 
       if (con.State.ToString() == "Open") 
       { 
        SqlCommand cmd = new SqlCommand(query, con); 
        cmd.ExecuteNonQuery(); 
        lastID = this.ToInt(cmd.ExecuteScalar()); 
       } 

       return this.ToInt(lastID); 
      } 
      catch 
      { 
       return 0; 
      } 
      } 
     } 
    } 
} 

Student.cs私のミスです

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Web;` 

namespace MyApp.Models 
{ 
    public class StudentModel 
    { 
     [StringLength(5)] 
     [Required] 
     [Display(Name = "Name:")] 
     public string productname { get; set; }` 

     [StringLength(3,MinimumLength=2,ErrorMessage="Min 5 max 10")] 
     [Required] 
     [Display(Name = "Quantitys:")] 
     public string quantity { get; set; } 

     [Required(ErrorMessage = "Please enter price.")] 
     public string price { get; set; } 
    } 
} 

のWeb.config

<connectionStrings> 
    <add name="DefaultConnection" 
     connectionString="Data Source=DESKTOP-VC6FUTV\SQLEXPRESS;Initial Catalog=MVC4;Persist Security Info=True;User ID=sa;Password=root" 
     providerName="System.Data.SqlClient" /> 
</connectionStrings> 

enter image description here

答えて

1

私はそれをテストしていませんが、私はあなたがここにSELECTと@@アイデンティティとの間のスペースが必要だと思う: String query = sql + ";[email protected]@Identity;";

私はあなたがDataInsertメソッド内のcatchブロックから0を取得していると思います。

また、クエリを2回実行しています。 cmd.ExecuteNonQuery();を削除します。

追加の注意として、ModelStateにエラーを追加する方法を再考することができます。 "エラー"はモデルのプロパティではありません(ModelState.AddModelError(string.Empty, "Save Error");)ので、この文のプロパティ名はModelState.AddModelError("Error", "Save Error");から削除します。プロパティー以外のエラー(「エラーの保存」など)を表示するには、ビューに検証サマリーが必要です。

関連する問題