c# - asp.net mvc / Sql double register -


i made new mvc project , made insert function db. problem when enter model db records twice. tried debugging, unfortunately couldn't find mistake. there miss in code below?

 public class dbcode     {         protected sqlconnection conn;          public bool open(string connection = "mydb")         {             conn = new sqlconnection(@webconfigurationmanager.connectionstrings[connection].tostring());             try             {                 var b = true;                 if (conn.state.tostring() != "open")                 {                     conn.open();                 }                 return b;             }             catch (sqlexception ex)             {                 return false;             }         }          public bool close()         {             try             {                 conn.close();                 return true;             }             catch (exception ex)             {                 return false;             }         }          public int toint(object s)         {             try             {                 return int32.parse(s.tostring());             }             catch (exception)             {                 return 0;             }          }          public int datainsert(string sql)         {             int lastid = 0;             string query = sql + ";select @@identity;";             try             {                 if (conn.state.tostring() == "open")                 {                     sqlcommand cmd = new sqlcommand(query, conn);                     cmd.executenonquery();                     lastid = this.toint(cmd.executescalar());                 }                 return this.toint(lastid);             }             catch             {                 return 0;             }         }     }    public class studentmodel     {         [required]         [stringlength(5)]         public string productname { get; set; }          [required]         [stringlength(5)]         public string quantity { get; set; }          [required]         [stringlength(5)]         public string price { get; set; }     } 

controller

 public class studentcontroller : controller     {         protected dbcode db = new dbcode();         public actionresult index()         {             return view();         }         [httppost]         [validateantiforgerytoken]         public actionresult savedatastudent(studentmodel student)         {             if (modelstate.isvalid)             {                 db.open();                 int = db.datainsert("insert tblproducts(productname,quantity,price) values('" + student.productname + "','" + student.quantity + "','" + student.price + "')");                 if (i > 0)                 {                     modelstate.addmodelerror("success", "save success");                 }                 else                 {                     modelstate.addmodelerror("error", "save error");                 }                 db.close();             }             return redirecttoaction("index", "student");         }     } 

student view

@model mvc5.models.studentmodel  @{     viewbag.title = "index"; }   @using (html.beginform("savedatastudent", "student", new { @id = "form" }, formmethod.post)) {     @html.validationsummary();     @html.antiforgerytoken();     @html.labelfor(m => m.productname);     @html.textboxfor(m => m.productname);<br/>      @html.labelfor(m => m.quantity);     @html.textboxfor(m => m.quantity);<br />      @html.labelfor(m => m.price);     @html.textboxfor(m => m.price);<br />      <input type="submit" value="save" name="save" /> } 

connection string in webconfig added

the problem lays in these lines:

cmd.executenonquery(); lastid = this.toint(cmd.executescalar()); 

you execute same command twice 2 records inserted database.

in order read last identity value define stored procedure insert data table , return last identity value. approach described here.

by way, there serious problems code. define sql command concatenating strings. of these strings come user side. means code vulnerable sql injection attack. instead should use parameters (see this or this).

i suggest not use magic constants in line conn.state.tostring() == "open" better approach use enumeration member: conn.state == connectionstate.open.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -