Reputation: 1209
i have a problem with auto incremental primary keys..
when im adding a student to my database, i can add the same student over and over again because the primary key of student is auto incremental so it is, of course, never repeated, i need to verify that the SSN of the student does not already exist in the database before inserting.
how can i do that on mvc3?? (im totally new in .net and mvc3)
my code for create in the student controller is:
[HttpPost]
public ActionResult Create(Alumno alumno)
{
try
{
using (var db = new administracionEntities())
{
db.Alumno.Add(alumno);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Upvotes: 1
Views: 993
Reputation: 936
In my model Class
public class Student {
public int StudentID { get; set; }
[Remote("UsernameChecker", "Student")]
public string Username { get; set; }
}
In my Controller
public virtual JsonResult UsernameChecker(string Username){
bool checkuser = db.Student.Any(i => i.Username == Username);
return checkuser
? Json("Username already exists", JsonRequestBehavior.AllowGet)
: Json(true, JsonRequestBehavior.AllowGet);
}
Upvotes: 0
Reputation: 2569
before you insert check if input alumno.ssn doesnot exist like
db.Alumno.where(a=> a.ssn == alumno.ssn).Any()
if this returns true, then there exists a ssn in database.
There are different ways in which you can achieve this in MVC.In one of which, You can have this call in a separate call to controller than in Create Action. May be you can check if duplicate SSN exists through JQuery.Ajax call on SSN textbox blur event on client side.
$.ajax({
type: "Get",
url: "StudentController/DoesSSNExist",
data: "ssn=#",
success: function(msg){
if(msg)
alert('ssn already exists');
}
This is controller action
public bool DoesSSNExist(string ssn)
{
return db.Alumno.where(a=> a.ssn == ssn).Any()
}
Upvotes: 1