0

In my MVC Application "TwentyFifth", Model is :

public class Student {
        public string StudentName { get; set; }
        public int StudentID { get; set; }
        public string FatherName { get; set; }
    }

A Method is Support-Class in Same Project is :

public void EditSupport(int id, Student std2)
        { 
            SqlConnection Con = new SqlConnection("Data Source=my;Initial Catalog=DB;Integrated Security=True");

            SqlCommand Com = new SqlCommand("update StudentT set StudentName='"+ std2.StudentName + "', FatherName='" + std2.FatherName + "' where StudentID=" + id + "", Con);

            Con.Open();
            Com.ExecuteNonQuery();
        }

And finally, Controller goes like :

[HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id, FormCollection formCollector)
        {            
            Student std = new Student();

            std.StudentID = id;
            std.StudentName = formCollector["StudentName"].ToString();
            std.FatherName = formCollector["FatherName"].ToString();

            BussinessNdataLayer bl = new BussinessNdataLayer();

            bl.EditSupport(id, std);

            return RedirectToAction("Index");
        }

Question : Why there is a Format Exception when I change Controller with ->

std.StudentID = Convert.ToInt32(formCollector["StudentID"]);

Note : at a break point I found string value in std.StudentID but with a Comma(,) Thanks for your reply.

Anas
  • 21
  • 4
  • 1
    hope [this](http://stackoverflow.com/a/1824349/1849444) help you – teo van kot Apr 25 '15 at 18:29
  • 1
    On a side note, I would use [parameterized SQL](http://stackoverflow.com/questions/542510/how-do-i-create-a-parameterized-sql-query-why-should-i). Concatenating SQL commands like this will leave you wide open to SQL Injection attacks. – QFDev Apr 25 '15 at 18:35

1 Answers1

0

The default model binder will handle all of this for you. Try changing your code to this so that the model binder does the conversion for you:

public ActionResult Edit_Post(int id, FormCollection formCollector, int StudentID)
{
    ...
    std.StudentID = StudentID;
    ...
}

It is best practice to never access the form collection directly and use strongly typed ViewModels and action method params instead.

Brad C
  • 2,868
  • 22
  • 33
  • thanks mate but still I am not very clear that what was the possible reason for value int std.Student to contain string value ending with comma (e.g. "0,") even after conversion. – Anas Apr 26 '15 at 18:50