asp.net mvc

kuhu kansal 1 Reputation point
2022-08-24T07:27:34.017+00:00

i m working on a asp.net mvc ,student management system , please help me How can i write create get function

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SMS.Models;

namespace SMS.Controllers
{
[Authorize(Roles ="Teachers,Admin")]
public class AssesmentsController : Controller
{
private SMSEntities db = new SMSEntities();

    // GET: Assesments  
    public ActionResult Index()  
    {  
        int id = Convert.ToInt32(Session["ID"]);  
        var department = db.Teaches.Where(d => d.TeacherId == id).Select(td => td.DepartmentId).ToList();  
        var year = db.Teaches.Where(d => d.TeacherId == id).Select(td => td.YearId);  
        var section = db.Teaches.Where(d => d.TeacherId == id).Select(td => td.SectionId);  
 //       var assesments = db.Assesments.Include(a => a.AssesmentType).Include(a => a.Course).Include(a => a.Department).Include(a => a.Section).Include(a => a.Year);  
        IEnumerable<Assesment> assesments = null;  
        foreach (var dept in department)  
        {  
            assesments = db.Assesments.Where(s => s.DepartmentID == dept.Value);  

            foreach (var y in year)  
            {  
                assesments = assesments.Where(s => s.YearID == y.Value);  
                foreach (var s in section)  
                {  
                    assesments = assesments.Where(x => x.YearID == s.Value);  
                }  
            }  
        }  
        if(assesments != null)  
        {  
            return View(assesments.ToList());  
        }  
        else  
        {  
            return View();  
        }  
          
    }  
    // GET: Assesments/Details/5  
    public ActionResult Details(int? id)  
    {  
        if (id == null)  
        {  
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
        }  
        Assesment assesment = db.Assesments.Find(id);  
        if (assesment == null)  
        {  
            return HttpNotFound();  
        }  
        return View(assesment);  
    }  

    // GET: Assesments/Create  
    public ActionResult Create()  
    {  
          
    }  

//// POST: Assesments/Create
//// To protect from overposting attacks, please enable the specific properties you want to bind to, for
//// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SysId,Id,Type,Time,GivenDate,DeadLine,SectionID,DepartmentID,CourseID,YearID,Title,Description,TotalMark,CreatedBy,IsDeleted")] Assesment assesment)
{
if (ModelState.IsValid)
{
//check whether selected department and yead takes that specific course
int studCourse = db.Courses.Where(c => c.SysId == assesment.CourseID && c.YearId == assesment.YearID).Count();
if (studCourse > 0)
{
assesment.CreatedBy = Convert.ToInt32(Session["ID"]);
db.Assesments.Add(assesment);
db.SaveChanges();
List<Result> resultList = new List<Result>();
Result result = new Result();
List<Student> studentList = db.Students.Where(x => x.SectionID == assesment.SectionID && x.YearID == assesment.YearID && x.DepartmentID == assesment.DepartmentID).ToList();
foreach (Student student in studentList)
{
result.StudentID = student.SysId;
result.AssessmentID = assesment.SysId;
result.CreatedBy = Convert.ToInt32(Session["TeacherSysID"]);
db.Results.Add(result);
db.SaveChanges();
}
return RedirectToAction("Index");
}
else
{
ViewBag.StudentCourse = "The Selected department or Year does not match with the selected course";
}
}

        ViewBag.Type = new SelectList(db.AssesmentTypes, "SysId", "Name", assesment.Type);  
        ViewBag.CourseID = new SelectList(db.Courses, "SysId", "Name", assesment.CourseID);  
        ViewBag.DepartmentID = new SelectList(db.Departments, "SysId", "Name", assesment.DepartmentID);  
        ViewBag.SectionID = new SelectList(db.Sections, "SysId", "Value", assesment.SectionID);  
        ViewBag.YearID = new SelectList(db.Years, "SysId", "Value", assesment.YearID);  
        return View();  
    }  

    //upload assesment  
    [HttpPost]  
    public ActionResult UploadAttachment(AssesmentAttachmentsModel membervalues)  
    {  
        if(membervalues.File != null)  
        {              
            string FileName = Path.GetFileNameWithoutExtension(membervalues.File.FileName);  
            string FileExtension = Path.GetExtension(membervalues.File.FileName);  
            FileName = FileName.Trim() + FileExtension;  
            //maps server path automatically  
            var path = Path.Combine(Server.MapPath("~/Content/SubmittedFiles/"), FileName);  
            //Its Create complete path to store in server.     
            membervalues.Attachment = path;  
            //To copy and save file into server.    
            membervalues.File.SaveAs(membervalues.Attachment);  
        }  
        Assesment assesment = new Assesment();   
        assesment.AssesmentType = membervalues.AssesmentType;  
        assesment.Attachment = membervalues.Attachment;  
        assesment.Course = membervalues.Course;  
        assesment.CourseID = membervalues.CourseID;  
        assesment.CreatedBy = Convert.ToInt32(Session["ID"]);  
        assesment.DeadLine = membervalues.DeadLine;  
        assesment.Department = membervalues.Department;  
        assesment.DepartmentID = membervalues.DepartmentID;  
        assesment.Description = membervalues.Description;  
        assesment.GivenDate = membervalues.GivenDate;  
        assesment.Id = membervalues.Id;  
        assesment.IsDeleted = membervalues.IsDeleted;  
        assesment.Section = membervalues.Section;  
        assesment.SectionID = membervalues.SectionID;  
        assesment.Teacher = membervalues.Teacher;  
        assesment.Time = membervalues.Time;  
        assesment.Title = membervalues.Title;  
        assesment.TotalMark = membervalues.TotalMark;  
        assesment.Type = membervalues.Type;  
        assesment.Year = membervalues.Year;  
        assesment.YearID = membervalues.YearID;  
      //  db.Assesments.Add(assesment);  
      //  db.SaveChanges();  
        if(Session["operation"].ToString() == "create")  
        {  
           return Create(assesment);  
           // return RedirectToAction("Create", assesment);  

        }  
        else if (Session["operation"].ToString() == "edit")  
        {  
            return Edit(assesment);  
        }  
          
        return RedirectToAction("Index");  
    }  

    // GET: Assesments/Edit/5  
    public ActionResult Edit(int? id)  
    {  
        if (id == null)  
        {  
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
        }  
        Assesment assesment = db.Assesments.Find(id);  
        Session["AssesmentCreatedDate"] = assesment.GivenDate;  
        Session["AssesmentDeadline"] = assesment.DeadLine;  
        Session["AssesmentAttachement"] = assesment.Attachment;  
        Session["AssesmentSysId"] = assesment.SysId;  
        if (assesment == null)  
        {  
            return HttpNotFound();  
        }  
        ViewBag.Type = new SelectList(db.AssesmentTypes, "SysId", "Name", assesment.Type);  
        ViewBag.CourseID = new SelectList(db.Courses, "SysId", "Name", assesment.CourseID);  
        ViewBag.DepartmentID = new SelectList(db.Departments, "SysId", "Name", assesment.DepartmentID);  
        ViewBag.SectionID = new SelectList(db.Sections, "SysId", "Value", assesment.SectionID);  
        ViewBag.YearID = new SelectList(db.Years, "SysId", "Value", assesment.YearID);  
        return View(assesment);  
    }  

    // POST: Assesments/Edit/5  
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.  
    [HttpPost]  
    [ValidateAntiForgeryToken]  
    public ActionResult Edit([Bind(Include = "SysId,Id,Type,Time,GivenDate,DeadLine,SectionID,DepartmentID,CourseID,YearID,Title,Description,TotalMark,CreatedBy,IsDeleted,Attachment")] Assesment assesment)  
    {  
        if (ModelState.IsValid)  
        {  
            assesment.CreatedBy = Convert.ToInt32(Session["ID"]);  
            assesment.GivenDate = DateTime.Parse(Session["AssesmentCreatedDate"].ToString());  
            assesment.SysId = Convert.ToInt32(Session["AssesmentSysId"].ToString());  
            assesment.Id =  Session["AssesmentSysId"].ToString();  
            if (assesment.Attachment==null)  
            {  
                if(Session["AssesmentAttachement"]!=null)  
                {  
                    assesment.Attachment = Session["AssesmentAttachement"].ToString();  
                }  
                  
            }  
            if(assesment.DeadLine == null)  
            {  
                assesment.DeadLine = DateTime.Parse(Session["AssesmentDeadline"].ToString());  
            }  
            db.Entry(assesment).State = EntityState.Modified;  
            db.SaveChanges();  
            return RedirectToAction("Index");  
        }  
        ViewBag.Type = new SelectList(db.AssesmentTypes, "SysId", "Name", assesment.Type);  
        ViewBag.CourseID = new SelectList(db.Courses, "SysId", "Name", assesment.CourseID);  
        ViewBag.DepartmentID = new SelectList(db.Departments, "SysId", "Name", assesment.DepartmentID);  
        ViewBag.SectionID = new SelectList(db.Sections, "SysId", "Value", assesment.SectionID);  
        ViewBag.YearID = new SelectList(db.Years, "SysId", "Value", assesment.YearID);  
        return View(assesment);  
    }  

    // GET: Assesments/Delete/5  
    public ActionResult Delete(int? id)  
    {  
        if (id == null)  
        {  
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
        }  
        Assesment assesment = db.Assesments.Find(id);  
        if (assesment == null)  
        {  
            return HttpNotFound();  
        }  
        return View(assesment);  
    }  

    // POST: Assesments/Delete/5  
    [HttpPost, ActionName("Delete")]  
    [ValidateAntiForgeryToken]  
    public ActionResult DeleteConfirmed(int id)  
    {  
        List<SubmitAssignment> submitAssignments = db.SubmitAssignments.Where(sa => sa.AssesmentId == id).ToList() ;  
        List<Result> results = db.Results.Where(r => r.AssessmentID == id).ToList();  
        foreach (SubmitAssignment sa in submitAssignments)  
        {   
            db.SubmitAssignments.Remove(sa);  
            db.SaveChanges();  
        }  
        foreach (Result r in results)  
        {  
            db.Results.Remove(r);  
            db.SaveChanges();  
        }  
        Assesment assesment = db.Assesments.Find(id);  
        db.Assesments.Remove(assesment);  
        db.SaveChanges();  
        return RedirectToAction("Index");  
    }  

    protected override void Dispose(bool disposing)  
    {  
        if (disposing)  
        {  
            db.Dispose();  
        }  
        base.Dispose(disposing);  
    }  
}  

}

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,246 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. QiYou-MSFT 4,306 Reputation points Microsoft Vendor
    2022-08-25T09:40:20.32+00:00

    Hi @kuhu kansal ,
    First you can edit the code in SMSEntities.cs:

    public class SMSEntities:DbContext  
        {  
          public SMSEntities() : base("SMSEntities")  
          {  
          }  
      
                public DbSet<Student> Students { get; set; }  
                public DbSet<Teacher> Teachers { get; set; }  
                public DbSet<Assesment> Assesments { get; set; }  
      
                protected override void OnModelCreating(DbModelBuilder modelBuilder)  
                {  
                    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
                }  
            }  
    

    Second, add data through the SaveChanges method.
    Controller:

    public class AssesmentController : Controller  
        {  
            private SMSEntities db = new SMSEntities();  
            public ActionResult Index()  
            {  
                return View(db.Assesments.ToList());  
            }  
           public ActionResult Create()  
            {  
                return View();  
            }  
            [HttpPost]  
            [ValidateAntiForgeryToken]  
            public ActionResult Create([Bind(Include = "Id,AssesmentId,SysId,Type,Time,GivenDate,DeadLine,SectionID,DepartmentID,CourseID,YearID,Title,Description,TotalMark,CreatedBy,IsDeleted,Attachment")] Assesment assesment)  
            {  
                if (ModelState.IsValid)  
                {  
                    db.Assesments.Add(assesment);  
                    db.SaveChanges();  
                    return RedirectToAction("Index");  
                }  
      
                return View(assesment);  
            }  
    

    View(Index):

    <h2>Index</h2>  
    <p>  
        @Html.ActionLink("Create New", "Create")  
    </p>  
    <table class="table">  
        <tr>  
            <th>  
                @Html.DisplayNameFor(model => model.AssesmentId)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.SysId)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Id)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Type)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Time)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.GivenDate)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.DeadLine)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.SectionID)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.DepartmentID)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.CourseID)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.YearID)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Title)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Description)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.TotalMark)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.CreatedBy)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.IsDeleted)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Attachment)  
            </th>  
            <th></th>  
        </tr>  
    @foreach (var item in Model) {  
    <tr>  
        <td>  
            @Html.DisplayFor(modelItem => item.AssesmentId)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.SysId)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Id)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Type)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Time)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.GivenDate)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.DeadLine)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.SectionID)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.DepartmentID)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.CourseID)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.YearID)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Title)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Description)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.TotalMark)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.CreatedBy)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.IsDeleted)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Attachment)  
        </td>  
      
    </tr>  
    }  
    </table>  
    

    Views(Create)

    @{  
        ViewBag.Title = "Create";  
    }  
      
    <h2>Create</h2>  
      
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
    <div class="form-horizontal">  
        <h4>Assesment</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })  
            </div>  
        </div>  
      
        <div class="form-group">  
            @Html.LabelFor(model => model.AssesmentId, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.AssesmentId, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.AssesmentId, "", new { @class = "text-danger" })  
            </div>  
        </div>  
      
        <div class="form-group">  
            @Html.LabelFor(model => model.SysId, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.SysId, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.SysId, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })  
           <div class="col-md-10">  
                @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.Time, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Time, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Time, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.GivenDate, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.GivenDate, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.GivenDate, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.DeadLine, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.DeadLine, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.DeadLine, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.SectionID, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.SectionID, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.SectionID, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.DepartmentID, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.DepartmentID, "", new { @class = "text-danger" })  
           </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.CourseID, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.CourseID, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.CourseID, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.YearID, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.YearID, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.YearID, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.TotalMark, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.TotalMark, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.TotalMark, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.CreatedBy, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.IsDeleted, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.IsDeleted, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.IsDeleted, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(model => model.Attachment, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Attachment, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Attachment, "", new { @class = "text-danger" })  
            </div>  
        </div>  
      
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
    }  
      
    <div>  
        @Html.ActionLink("Back to List", "Index")  
    </div>  
      
    @section Scripts {  
        @Scripts.Render("~/bundles/jqueryval")  
    }  
    

    If you want to know more, you can check:
    https://learn.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/
    Best regards,
    Youqi


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments