(MVC) MVC (2018)

<<назад StudentsController2.vb (Contoso University).

   1:  '#Const Type = "DirectScaffold"
   2:  'or --------------------
   3:  '#Const Type1 = "ScaffoldedIndex"
   4:  '#Const Type1 = "SortOnly"
   5:  '#Const Type1 = "SortFilter"
   6:  #Const Type1 = "SortFilterPage"
   7:  '#Const Type1 = "DynamicLinq"
   8:  '--------------------------
   9:  '#Const Type2 = "ReadFirst"
  10:  #Const Type2 = "CreateAndAttach"
  11:  '--------------------------
  12:  #Const Type3 = "DeleteWithReadFirst"
  13:  '#Const Type3 = "DeleteWithoutReadFirst"
  14:   
  15:  Imports System
  16:  Imports System.Collections.Generic
  17:  Imports System.Data
  18:  Imports System.Data.Entity
  19:  Imports System.Linq
  20:  Imports System.Threading.Tasks
  21:  Imports System.Net
  22:  Imports System.Web
  23:  Imports System.Web.Mvc
  24:  Imports CU_VB_3
  25:  Imports CU_VB_3.Models
  26:  Imports System.Data.Entity.Infrastructure
  27:  Imports System.IdentityModel.Metadata
  28:  Imports System.Collections.ObjectModel
  29:   
  30:  Namespace Controllers
  31:      Public Class StudentsController
  32:          Inherits System.Web.Mvc.Controller
  33:   
  34:  #If Type = "DirectScaffold" Then
  35:  #Region "DirectScaffold"
  36:          Private db As New SchoolContext
  37:   
  38:          ' GET: Students
  39:          Async Function Index() As Task(Of ActionResult)
  40:              Return View(Await Task.FromResult(db.Students.ToList()))
  41:          End Function
  42:   
  43:          ' GET: Students/Details/5
  44:          Async Function Details(ByVal id As Integer?) As Task(Of ActionResult)
  45:              If IsNothing(id) Then
  46:                  Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
  47:              End If
  48:              Dim student As Student = Await db.People.FindAsync(id)
  49:              If IsNothing(student) Then
  50:                  Return HttpNotFound()
  51:              End If
  52:              Return View(student)
  53:          End Function
  54:   
  55:          ' GET: Students/Create
  56:          Function Create() As ActionResult
  57:              Return View()
  58:          End Function
  59:   
  60:          ' POST: Students/Create
  61:          'To protect from overposting attacks, please enable the specific properties you want to bind to, for 
  62:          'more details see https://go.microsoft.com/fwlink/?LinkId=317598.
  63:          <HttpPost()>
  64:          <ValidateAntiForgeryToken()>
  65:          Async Function Create(<Bind(Include:="ID,LastName,FirstMidName,EnrollmentDate")> ByVal student As Student) As Task(Of ActionResult)
  66:              If ModelState.IsValid Then
  67:                  db.People.Add(student)
  68:                  Await db.SaveChangesAsync()
  69:                  Return RedirectToAction("Index")
  70:              End If
  71:              Return View(student)
  72:          End Function
  73:   
  74:          ' GET: Students/Edit/5
  75:          Async Function Edit(ByVal id As Integer?) As Task(Of ActionResult)
  76:              If IsNothing(id) Then
  77:                  Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
  78:              End If
  79:              Dim student As Student = Await db.People.FindAsync(id)
  80:              If IsNothing(student) Then
  81:                  Return HttpNotFound()
  82:              End If
  83:              Return View(student)
  84:          End Function
  85:   
  86:          ' POST: Students/Edit/5
  87:          'To protect from overposting attacks, please enable the specific properties you want to bind to, for 
  88:          'more details see https://go.microsoft.com/fwlink/?LinkId=317598.
  89:          <HttpPost()>
  90:          <ValidateAntiForgeryToken()>
  91:          Async Function Edit(<Bind(Include:="ID,LastName,FirstMidName,EnrollmentDate")> ByVal student As Student) As Task(Of ActionResult)
  92:              If ModelState.IsValid Then
  93:                  db.Entry(student).State = EntityState.Modified
  94:                  Await db.SaveChangesAsync()
  95:                  Return RedirectToAction("Index")
  96:              End If
  97:              Return View(student)
  98:          End Function
  99:   
 100:          ' GET: Students/Delete/5
 101:          Async Function Delete(ByVal id As Integer?) As Task(Of ActionResult)
 102:              If IsNothing(id) Then
 103:                  Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
 104:              End If
 105:              Dim student As Student = Await db.People.FindAsync(id)
 106:              If IsNothing(student) Then
 107:                  Return HttpNotFound()
 108:              End If
 109:              Return View(student)
 110:          End Function
 111:   
 112:          ' POST: Students/Delete/5
 113:          <HttpPost()>
 114:          <ActionName("Delete")>
 115:          <ValidateAntiForgeryToken()>
 116:          Async Function DeleteConfirmed(ByVal id As Integer) As Task(Of ActionResult)
 117:              Dim student As Student = Await db.People.FindAsync(id)
 118:              db.People.Remove(student)
 119:              Await db.SaveChangesAsync()
 120:              Return RedirectToAction("Index")
 121:          End Function
 122:   
 123:          Protected Overrides Sub Dispose(ByVal disposing As Boolean)
 124:              If (disposing) Then
 125:                  db.Dispose()
 126:              End If
 127:              MyBase.Dispose(disposing)
 128:          End Sub
 129:  #End Region
 130:  #End If
 131:          Private ReadOnly _context As SchoolContext
 132:          Public Sub New(ByVal context As SchoolContext)
 133:              _context = context
 134:          End Sub
 135:          Public Sub New()
 136:              _context = New SchoolContext
 137:          End Sub
 138:   
 139:  #If Type1 = "ScaffoldedIndex" Then
 140:   
 141:          Public Async Function Index() As Task(Of ActionResult)
 142:              Return View(Await _context.Students.ToListAsync())
 143:          End Function
 144:  #ElseIf Type1 = "SortOnly" Then
 145:   
 146:         Public Async Function Index(ByVal sortOrder As String) As Task(Of ActionResult)
 147:              ViewData("NameSortParm") = If(String.IsNullOrEmpty(sortOrder), "name_desc", "")
 148:              ViewData("DateSortParm") = If(sortOrder = "Date", "date_desc", "Date")
 149:              Dim students = From s In _context.Students Select s
 150:   
 151:              Select Case sortOrder
 152:                  Case "name_desc"
 153:                      students = students.OrderByDescending(Function(s) s.LastName)
 154:                  Case "Date"
 155:                      students = students.OrderBy(Function(s) s.EnrollmentDate)
 156:                  Case "date_desc"
 157:                      students = students.OrderByDescending(Function(s) s.EnrollmentDate)
 158:                  Case Else
 159:                      students = students.OrderBy(Function(s) s.LastName)
 160:              End Select
 161:   
 162:              Return View(Await students.AsNoTracking().ToListAsync())
 163:          End Function
 164:  #ElseIf Type1 = "SortFilter" Then
 165:   
 166:          Public Async Function Index(ByVal sortOrder As String, ByVal searchString As String) As Task(Of ActionResult)
 167:              ViewData("NameSortParm") = If(String.IsNullOrEmpty(sortOrder), "name_desc", "")
 168:              ViewData("DateSortParm") = If(sortOrder = "Date", "date_desc", "Date")
 169:              ViewData("CurrentFilter") = searchString
 170:              Dim students = From s In _context.Students Select s
 171:   
 172:              If Not String.IsNullOrEmpty(searchString) Then
 173:                  students = students.Where(Function(s) s.LastName.Contains(searchString) OrElse s.FirstMidName.Contains(searchString))
 174:              End If
 175:   
 176:              Select Case sortOrder
 177:                  Case "name_desc"
 178:                      students = students.OrderByDescending(Function(s) s.LastName)
 179:                  Case "Date"
 180:                      students = students.OrderBy(Function(s) s.EnrollmentDate)
 181:                  Case "date_desc"
 182:                      students = students.OrderByDescending(Function(s) s.EnrollmentDate)
 183:                  Case Else
 184:                      students = students.OrderBy(Function(s) s.LastName)
 185:              End Select
 186:   
 187:              Return View(Await students.AsNoTracking().ToListAsync())
 188:          End Function
 189:  #ElseIf Type1 = "SortFilterPage" Then
 190:   
 191:          Public Async Function Index(ByVal sortOrder As String, ByVal currentFilter As String, ByVal searchString As String, ByVal page As Integer?) As Task(Of ActionResult)
 192:              ViewData("CurrentSort") = sortOrder
 193:              ViewData("NameSortParm") = If(String.IsNullOrEmpty(sortOrder), "name_desc", "")
 194:              ViewData("DateSortParm") = If(sortOrder = "Date", "date_desc", "Date")
 195:   
 196:              If searchString IsNot Nothing Then
 197:                  page = 1
 198:              Else
 199:                  searchString = currentFilter
 200:              End If
 201:   
 202:              ViewData("CurrentFilter") = searchString
 203:              Dim students = From s In _context.Students Select s
 204:   
 205:              If Not String.IsNullOrEmpty(searchString) Then
 206:                  students = students.Where(Function(s) s.LastName.Contains(searchString) OrElse s.FirstMidName.Contains(searchString))
 207:              End If
 208:   
 209:              Select Case sortOrder
 210:                  Case "name_desc"
 211:                      students = students.OrderByDescending(Function(s) s.LastName)
 212:                  Case "Date"
 213:                      students = students.OrderBy(Function(s) s.EnrollmentDate)
 214:                  Case "date_desc"
 215:                      students = students.OrderByDescending(Function(s) s.EnrollmentDate)
 216:                  Case Else
 217:                      students = students.OrderBy(Function(s) s.LastName)
 218:              End Select
 219:   
 220:              Dim pageSize As Integer = 3
 221:              Return View(Await PaginatedList(Of Student).CreateAsync(students.AsNoTracking(), If(page, 1), pageSize))
 222:          End Function
 223:   
 224:  #ElseIf Type1 = "DynamicLinq" Then
 225:   
 226:          Public Async Function Index(ByVal sortOrder As String, ByVal currentFilter As String, ByVal searchString As String, ByVal page As Integer?) As Task(Of IActionResult)
 227:              ViewData("CurrentSort") = sortOrder
 228:              ViewData("NameSortParm") = If(String.IsNullOrEmpty(sortOrder), "LastName_desc", "")
 229:              ViewData("DateSortParm") = If(sortOrder = "EnrollmentDate", "EnrollmentDate_desc", "EnrollmentDate")
 230:   
 231:              If searchString IsNot Nothing Then
 232:                  page = 1
 233:              Else
 234:                  searchString = currentFilter
 235:              End If
 236:   
 237:              ViewData("CurrentFilter") = searchString
 238:              Dim students = From s In _context.Students Select s
 239:   
 240:              If Not String.IsNullOrEmpty(searchString) Then
 241:                  students = students.Where(Function(s) s.LastName.Contains(searchString) OrElse s.FirstMidName.Contains(searchString))
 242:              End If
 243:   
 244:              If String.IsNullOrEmpty(sortOrder) Then
 245:                  sortOrder = "LastName"
 246:              End If
 247:   
 248:              Dim descending As Boolean = False
 249:   
 250:              If sortOrder.EndsWith("_desc") Then
 251:                  sortOrder = sortOrder.Substring(0, sortOrder.Length - 5)
 252:                  descending = True
 253:              End If
 254:   
 255:              If descending Then
 256:                  students = students.OrderByDescending(Function(e) EF.[Property](Of Object)(e, sortOrder))
 257:              Else
 258:                  students = students.OrderBy(Function(e) EF.[Property](Of Object)(e, sortOrder))
 259:              End If
 260:   
 261:              Dim pageSize As Integer = 3
 262:              Return View(Await PaginatedList(Of Student).CreateAsync(students.AsNoTracking(), If(page, 1), pageSize))
 263:          End Function
 264:  #End If
 265:   
 266:          Public Async Function Details(ByVal id As Integer?) As Task(Of ActionResult)
 267:              If id Is Nothing Then
 268:                  Return HttpNotFound()
 269:              End If
 270:   
 271:              Dim student = Await _context.Students.Include(Function(s) s.Enrollments).AsNoTracking().SingleOrDefaultAsync(Function(m) m.ID = id)
 272:              '.ThenInclude(Function(e) e.Course).AsNoTracking().SingleOrDefaultAsync(Function(m) m.ID = id)
 273:   
 274:              If student Is Nothing Then
 275:                  Return HttpNotFound()t
 276:              End If
 277:   
 278:              Return View(student)
 279:          End Function
 280:   
 281:          Public Function Create() As ActionResult
 282:              Return View()
 283:          End Function
 284:   
 285:          <HttpPost>
 286:          <ValidateAntiForgeryToken>
 287:          Public Async Function Create(<Bind(Include:="EnrollmentDate,FirstMidName,LastName")> ByVal student As Student) As Task(Of ActionResult)
 288:              Try
 289:                  If ModelState.IsValid Then
 290:                      _context.Add(student)
 291:                      Await _context.SaveChangesAsync()
 292:                      Return RedirectToAction(NameOf(Index))
 293:                  End If
 294:   
 295:              Catch __unusedDbUpdateException1__ As DbUpdateException
 296:                  ModelState.AddModelError("", "Unable to save changes. " & "Try again, and if the problem persists " & "see your system administrator.")
 297:              End Try
 298:   
 299:              Return View(student)
 300:          End Function
 301:   
 302:          'Edit Get
 303:          Public Async Function Edit(ByVal id As Integer?) As Task(Of ActionResult)
 304:              If id Is Nothing Then
 305:                  Return HttpNotFound()
 306:              End If
 307:   
 308:              Dim student = Await _context.Students.AsNoTracking().SingleOrDefaultAsync(Function(m) m.ID = id)
 309:   
 310:              If student Is Nothing Then
 311:                  Return HttpNotFound()
 312:              End If
 313:   
 314:              Return View(student)
 315:          End Function
 316:   
 317:  #If Type2 = "ReadFirst" Then
 318:   
 319:          <HttpPost, ActionName("Edit")>
 320:          <ValidateAntiForgeryToken>
 321:          Public Async Function EditPost(ByVal id As Integer?) As Task(Of ActionResult)
 322:              If id Is Nothing Then
 323:                  Return HttpNotFound()
 324:              End If
 325:   
 326:              Dim studentToUpdate = Await _context.Students.SingleOrDefaultAsync(Function(s) s.ID = id)
 327:   
 328:              If Await TryUpdateModelAsync(Of Student)(studentToUpdate, "", Function(s) s.FirstMidName, Function(s) s.LastName, Function(s) s.EnrollmentDate) Then
 329:   
 330:                  Try
 331:                      Await _context.SaveChangesAsync()
 332:                      Return RedirectToAction(NameOf(Index))
 333:                  Catch __unusedDbUpdateException1__ As DbUpdateException
 334:                      ModelState.AddModelError("", "Unable to save changes. " & "Try again, and if the problem persists, " & "see your system administrator.")
 335:                  End Try
 336:              End If
 337:   
 338:              Return View(studentToUpdate)
 339:          End Function
 340:   
 341:  #ElseIf Type2 = "CreateAndAttach" Then
 342:   
 343:   
 344:   
 345:          <HttpPost, ActionName("Edit")>
 346:          <ValidateAntiForgeryToken>
 347:          Public Async Function Edit(ByVal id As Integer, <Bind(Include:="ID,EnrollmentDate,FirstMidName,LastName")> ByVal student As Student) As Task(Of ActionResult)
 348:              If id <> student.ID Then
 349:                  Return HttpNotFound()
 350:              End If
 351:   
 352:              If ModelState.IsValid Then
 353:   
 354:                  Try
 355:                      _context.Update(student)
 356:                      Await _context.SaveChangesAsync()
 357:                      Return RedirectToAction(NameOf(Index))
 358:                  Catch __unusedDbUpdateException1__ As DbUpdateException
 359:                      ModelState.AddModelError("", "Unable to save changes. " & "Try again, and if the problem persists, " & "see your system administrator.")
 360:                  End Try
 361:              End If
 362:   
 363:              Return View(student)
 364:          End Function
 365:  #End If
 366:   
 367:   
 368:          'delete Get
 369:          Public Async Function Delete(ByVal id As Integer?, ByVal Optional saveChangesError As Boolean? = False) As Task(Of ActionResult)
 370:              If id Is Nothing Then
 371:                  Return HttpNotFound()
 372:              End If
 373:   
 374:              Dim student = Await _context.Students.AsNoTracking().SingleOrDefaultAsync(Function(m) m.ID = id)
 375:   
 376:              If student Is Nothing Then
 377:                  Return HttpNotFound()
 378:              End If
 379:   
 380:              If saveChangesError.GetValueOrDefault() Then
 381:                  ViewData("ErrorMessage") = "Delete failed. Try again, and if the problem persists " & "see your system administrator."
 382:              End If
 383:   
 384:              Return View(student)
 385:          End Function
 386:   
 387:   
 388:  #If Type3 = "DeleteWithReadFirst" Then
 389:   
 390:          <HttpPost, ActionName("Delete")>
 391:          <ValidateAntiForgeryToken>
 392:          Public Async Function DeleteConfirmed(ByVal id As Integer) As Task(Of ActionResult)
 393:              Dim student = Await _context.Students.AsNoTracking().SingleOrDefaultAsync(Function(m) m.ID = id)
 394:   
 395:              If student Is Nothing Then
 396:                  Return RedirectToAction(NameOf(Index))
 397:              End If
 398:   
 399:              Try
 400:                  _context.Students.Remove(student)
 401:                  Await _context.SaveChangesAsync()
 402:                  Return RedirectToAction(NameOf(Index))
 403:              Catch __unusedDbUpdateException1__ As DbUpdateException
 404:                  Return RedirectToAction(NameOf(Delete), New With {
 405:                      .id = id,
 406:                      .saveChangesError = True
 407:                  })
 408:              End Try
 409:          End Function
 410:   
 411:  #ElseIf Type3 = "DeleteWithoutReadFirst" Then
 412:   
 413:          <HttpPost>
 414:          <ValidateAntiForgeryToken>
 415:          Public Async Function DeleteConfirmed(ByVal id As Integer) As Task(Of ActionResult)
 416:              Try
 417:                  Dim studentToDelete As Student = New Student() With {
 418:                      .ID = id
 419:                  }
 420:                  _context.Entry(studentToDelete).State = EntityState.Deleted
 421:                  Await _context.SaveChangesAsync()
 422:                  Return RedirectToAction(NameOf(Index))
 423:              Catch __unusedDbUpdateException1__ As DbUpdateException
 424:                  Return RedirectToAction(NameOf(Delete), New With {
 425:              .id = id,
 426:              .saveChangesError = True
 427:          })
 428:              End Try
 429:   
 430:          End Function
 431:  #End If
 432:   
 433:      End Class
 434:  End Namespace


Comments ( )
Link to this page: //www.vb-net.com/EF-missing-FAQ/Code/Students-StudentsController2.vb.htm
< THANKS ME>