Saya memiliki Dua aplikasi ASP.net Core 3 berbeda yang sedang berjalan yang memiliki Tabel yang ditautkan ke tabel lain dengan kunci asing. Di halaman CRUD, daftar Drop-down berfungsi dengan baik dan menampilkan data tetapi data diurutkan dalam urutan kunci utama, yang biasanya merupakan kunci indeks bilangan bulat. Saya berharap dapat menemukan cara menampilkan daftar dropdown ini dalam urutan berdasarkan nilai yang ditampilkan. Saya belum menemukan perintah yang melakukan pekerjaan itu. Bantuan apa pun akan dihargai. Kunci asing untuk Proyek adalah Jalan dan Properti Kota. Saya akan melampirkan file kode;

Pengontrol Proyek.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using TOGProjects.Models;

namespace TOGProjects.Controllers
{
    public class ProjectsController : Controller
    {
        private readonly TOGProjectsContext _context;

        public ProjectsController(TOGProjectsContext context)
        {
            _context = context;
        }

        // GET: Projects
        public async Task<IActionResult> Index()
        {
            var tOGProjectsContext = _context.Projects.Include(p => p.Street).Include(p => p.TownProperty);
            return View(await tOGProjectsContext.ToListAsync());
        }

        // add Search ablity on the Index Page
        [HttpGet]
        public async Task<IActionResult> Index(String Projectsearch)
        {
            ViewData["GetProjectDetails"] = Projectsearch;

            var projectquery = _context.Projects
                                    .Include(s => s.Street)
                                    .Include(s => s.TownProperty)
                                    .AsQueryable();



            if (!String.IsNullOrEmpty(Projectsearch))
            {
                projectquery = projectquery.Where(x => x.ProjectDescription.Contains(Projectsearch) || x.Pwnum.Contains(Projectsearch));
            }
            return View(await projectquery.AsNoTracking().ToListAsync());
        }

        // GET: Projects/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var projects = await _context.Projects
                .Include(p => p.Street)
                .Include(p => p.TownProperty)
                .FirstOrDefaultAsync(m => m.ProjectId == id);
            if (projects == null)
            {
                return NotFound();
            }

            return View(projects);
        }

        // GET: Projects/Create
        public IActionResult Create()
        {
            ViewData["StreetId"] = new SelectList(_context.StreetNames, "StreetId", "Streets");
            ViewData["TownPropertyId"] = new SelectList(_context.TownProperties, "TownPropertyId", "TownPropertyName");
            return View();
        }

        // POST: Projects/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ProjectId,ProjectDescription,DateStarted,Pwnum,StreetId,StateProjectNumber,TownPropertyId,CapitalAccount")] Projects projects)
        {
            if (ModelState.IsValid)
            {
                _context.Add(projects);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["StreetId"] = new SelectList(_context.StreetNames, "StreetId", "Streets", projects.StreetId);
            ViewData["TownPropertyId"] = new SelectList(_context.TownProperties, "TownPropertyId", "TownPropertyName", projects.TownPropertyId);
            return View(projects);
        }

        // GET: Projects/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var projects = await _context.Projects.FindAsync(id);
            if (projects == null)
            {
                return NotFound();
            }
            ViewData["StreetId"] = new SelectList(_context.StreetNames, "StreetId", "Streets", projects.StreetId);
            ViewData["TownPropertyId"] = new SelectList(_context.TownProperties, "TownPropertyId", "TownPropertyName", projects.TownPropertyId);
            return View(projects);
        }

        // POST: Projects/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ProjectId,ProjectDescription,DateStarted,Pwnum,StreetId,StateProjectNumber,TownPropertyId,CapitalAccount")] Projects projects)
        {
            if (id != projects.ProjectId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(projects);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProjectsExists(projects.ProjectId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["StreetId"] = new SelectList(_context.StreetNames, "StreetId", "Streets", projects.StreetId);
            ViewData["TownPropertyId"] = new SelectList(_context.TownProperties, "TownPropertyId", "TownPropertyName", projects.TownPropertyId);
            return View(projects);
        }

        // GET: Projects/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var projects = await _context.Projects
                .Include(p => p.Street)
                .Include(p => p.TownProperty)
                .FirstOrDefaultAsync(m => m.ProjectId == id);
            if (projects == null)
            {
                return NotFound();
            }

            return View(projects);
        }

        // POST: Projects/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var projects = await _context.Projects.FindAsync(id);
            _context.Projects.Remove(projects);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ProjectsExists(int id)
        {
            return _context.Projects.Any(e => e.ProjectId == id);
        }
    }
}

Projects.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace TOGProjects.Models
{
    public partial class Projects
    {
        public int ProjectId { get; set; }
        [DisplayName("Project Description")]
        [Required, StringLength(50)]
        [RegularExpression(@"(([A-za-z0-9\s\-]+))$")]
        public string ProjectDescription { get; set; }
        [DisplayName("Date Started")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime? DateStarted { get; set; }
        [DisplayName("Engineering Project Number")]
        public string Pwnum { get; set; }
        public int? StreetId { get; set; }
        [DisplayName("State Project Number")]
        [StringLength(15)]
        public string StateProjectNumber { get; set; }
        public int? TownPropertyId { get; set; }
        [DisplayName("Capital Account")]
        [StringLength(30)]
        public string CapitalAccount { get; set; }

        public virtual StreetNames Street { get; set; }
        [DisplayName("Town Property Name")]
        [StringLength(50)]
        public virtual TownProperties TownProperty { get; set; }
    }
}

Proyek Index.cshtml

@model TOGProjects.Models.Projects

@{
    ViewData["Title"] = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Edit</h1>

<h4>Projects</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ProjectId" />
            <div class="form-group">
                <label asp-for="ProjectDescription" class="control-label"></label>
                <input asp-for="ProjectDescription" class="form-control" />
                <span asp-validation-for="ProjectDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DateStarted" class="control-label"></label>
                <input asp-for="DateStarted" class="form-control" />
                <span asp-validation-for="DateStarted" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Pwnum" class="control-label"></label>
                <input asp-for="Pwnum" class="form-control" />
                <span asp-validation-for="Pwnum" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="StreetId" class="control-label"></label>
                <select asp-for="StreetId" class="form-control" asp-items="ViewBag.StreetId"></select>
                <span asp-validation-for="StreetId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="StateProjectNumber" class="control-label"></label>
                <input asp-for="StateProjectNumber" class="form-control" />
                <span asp-validation-for="StateProjectNumber" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TownPropertyId" class="control-label"></label>
                <select asp-for="TownPropertyId" class="form-control" asp-items="ViewBag.TownPropertyId"></select>
                <span asp-validation-for="TownPropertyId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CapitalAccount" class="control-label"></label>
                <input asp-for="CapitalAccount" class="form-control" />
                <span asp-validation-for="CapitalAccount" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Terima kasih

0
Bashtonmcse 7 Maret 2020, 01:21

1 menjawab

Jawaban Terbaik

Anda perlu menambahkan OrderBy ke data Anda seperti di bawah ini.

ViewData["StreetId"] = new SelectList(_context.StreetNames.OrderBy(s => s.Streets), "StreetId", "Streets");
ViewData["TownPropertyId"] = new SelectList(_context.TownProperties.OrderBy(t => t.TownPropertyName), "TownPropertyId", "TownPropertyName");
1
JammoD 7 Maret 2020, 00:39