需要比较其他表的价值

时间:2017-11-05 13:00:21

标签: c# asp.net asp.net-mvc

我的模型中有3个课程

模型

public class Student  
{  
public int id { get; set; }  
[Required]  
[DisplayName("Student Name")]  
public string Name { get; set; }  
[Required]  
public int RollNO { get; set; }  
public DateTime EnrollmentDate { get; set; }  
public ICollection<Record> Records { get; set; }  
}  

public class Record  
{  
public int Id { get; set; }  
public int StudentId { get; set; }  
public int SubjectId { get; set; }  
[Required]  
public int Marks { get; set; }  
public string Result { get; set; }  
public virtual Student Students { get; set; }  
public virtual Subject Subjects { get; set; }  
}  

public class Subject  
{  
public int id { get; set; }  
[Required]  
public string Title { get; set; }  
[Required]  
[DisplayName("Minimum Marks")]  
public int MinMarks { get; set; }  
[Required]  
[DisplayName("Max Marks")]  
public int MaxMarks { get; set; }  
public ICollection<Record> Records { get; set; }  
} 

在主题表中,我将创建每个主题并设置通过所需的最小和最大标记...现在在记录表(创建页面)中我想要将所选主题最小标记与Record.Marks进行比较,如果少于Record.Result中的最小标记得到失败,如果它的大于最大标记在Record.Result中得到Pass ...我还想比较Result.Marks属性和Subject.MaxMarks,如果它大于Subject.MaxMarks用户应该以任何形式得到错误......

这是我的控制器

控制器

public ActionResult Create([Bind(Include = "Id,StudentId,SubjectId,Marks,Result")] Record record,Subject subject)
{

    var selectedSubject = db.Subjects.Where(sub => subject.id == record.SubjectId).FirstOrDefault();

    if (record.Marks < selectedSubject.MinMarks)
    {
        record.Result = "Fail";
    }
    else
        record.Result = "Pass";

    if (ModelState.IsValid)
    {
        db.Records.Add(record);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.StudentId = new SelectList(db.Students, "id", "Name", record.StudentId);
    ViewBag.SubjectId = new SelectList(db.Subjects, "id", "Title", record.SubjectId);
    return View(record);
}

1 个答案:

答案 0 :(得分:0)

假设您的视图具有选择/输入主题ID的输入元素,并且元素的名称属性值为SubjectId且它位于form

如果要检查最大标记,只需添加其他内容即可。您的action方法中不需要第二个参数。只需删除它。

var selectedSubject = db.Subjects.FirstOrDefault(a=> a.id == record.SubjectId);
if(selectedSubject!=null)
{     

  if (record.Marks < selectedSubject.MinMarks)
  {
    record.Result = "Fail";
  }
  else if (record.Marks > selectedSubject.MaxMarks)
  {
    record.Result = "Error";
  }
  else
  {
    record.Result = "Pass";
  }
}
else
{
  ModelState.AddModeError(string.empty,"Subject not found");
}
//to do : Reload dropdown data and return the view