ASP MVC Model ID没有传递给actionlink

时间:2016-09-05 10:02:18

标签: asp.net-mvc entity-framework razor

我的观点是没有获取自动生成的编辑/详细信息操作链接中的模型ID。相反,它只是将我链接到hostname / controller / id而不是;主机名/控制器/信息/ ID

大多数情况下它只使用自动生成的代码;没有太大的变化 - 只是添加搜索&排序等。

我毫不怀疑它是一件非常愚蠢的事!

谢谢你们

型号:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace SMS_ADM.Models
{
    public class Logger
    {

        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Serial is required - This is the ID number of the weather station.")]        
        [DisplayName("Station Serial")]        
        public int Serial { get; set; }

        [DisplayName("Friendly Name")]
        public string Friendlyname { get; set; }

        [Required(ErrorMessage = "Location is required - Please select the location where the weather station physically resides.")]
        [DisplayName("Location")]
        public int Locationid { get; set; }

        [DisplayName("Location")]
        public virtual Location Location { get; set; }       

    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SMS_ADM.Models;
using System.Web.WebPages.Html;

namespace SMS_ADM.Controllers
{
    public class LoggersController : Controller
    {
        private SmsadmContext db = new SmsadmContext();

        // GET: Loggers
        public ActionResult Index()
        {
            var loggers = db.Loggers.Include(l => l.Location);

         return View(loggers.ToList());

          //  return View();

        }

        // GET: Loggers/Details/5
        public ActionResult Details(int? Id)
        {
            if (Id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Logger logger = db.Loggers.Find(Id);
            if (logger == null)
            {
                return HttpNotFound();
            }
            return View(logger);
        }

        // GET: Loggers/Create
        public ActionResult Create()
        {
            ViewBag.locationid = new System.Web.Mvc.SelectList(db.Locations, "Id", "locationname");
            return View();
        }

        // POST: Loggers/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 ActionResult Create([Bind(Include = "serial,friendlyname,locationid")] Logger logger, Logger model)
        {
            ViewBag.locationid = new System.Web.Mvc.SelectList(db.Locations, "Id", "locationname");

            if (ModelState.IsValid)
            {

                if (db.Loggers.Any(o => o.Serial == logger.Serial))
                {
                    //exists
                    ModelState.AddModelError(string.Empty, "Weather station serial number already exists in system.");
                    return View();
                }
                else
                {
                    db.Loggers.Add(logger);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            return View(logger);
        }

        // GET: Loggers/Edit/5
        public ActionResult Edit(int? Id)
        {
            if (Id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Logger logger = db.Loggers.Find(Id);
            if (logger == null)
            {
                return HttpNotFound();
            }
            ViewBag.locationid = new SelectList(db.Locations, "Id", "locationcode", logger.Locationid);
            return View(logger);
        }

        // POST: Loggers/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 ActionResult Edit([Bind(Include = "Id,serial,friendlyname,locationid")] Logger logger)
        {
            if (ModelState.IsValid)
            {
                db.Entry(logger).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.locationid = new SelectList(db.Locations, "Id", "locationcode", logger.Locationid);
            return View(logger);
        }

        // GET: Loggers/Delete/5
        public ActionResult Delete(int? Id)
        {
            if (Id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Logger logger = db.Loggers.Find(Id);
            if (logger == null)
            {
                return HttpNotFound();
            }
            return View(logger);
        }

        // POST: Loggers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int Id)
        {
            Logger logger = db.Loggers.Find(Id);
            db.Loggers.Remove(logger);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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

查看:

@model IEnumerable<SMS_ADM.Models.Logger>

@{
    ViewBag.Title = "Weather Stations List";
}

<h2>@ViewBag.title</h2>

<p>
    @Html.ActionLink("Register New Weather Station", "Create")
</p>
@using (Html.BeginForm())
{
    <p>
        Search: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />
    </p>
}
<table class="table">
    <tr>
        <th>
            @Html.ActionLink("DBID", "Index", new { sortOrder = ViewBag.lcodeSortParm })
        </th>
        <th>
            @Html.ActionLink("Location Code", "Index", new {sortOrder = ViewBag.lcodeSortParm})
        </th>
        <th>
            @Html.ActionLink("Serial", "Index", new {sortOrder = ViewBag.serialSortParm})
        </th>
        <th>
            @Html.ActionLink("Friendly Name", "Index", new {sortOrder = ViewBag.fnameSortParm})
        </th>
        <th>
            @Html.ActionLink("Site", "Index", new {sortOrder = ViewBag.siteSortParm})
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.Location.Locationcode)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.Serial)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Friendlyname)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.Location.Site)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new {Id = item.Id}, null) |
            @Html.ActionLink("Details", "Details", new {Id = item.Id}) |
            @Html.ActionLink("Delete", "Delete", new {Id = item.Id})
        </td>
    </tr>
}

</table>

1 个答案:

答案 0 :(得分:0)

好的 - 发布后我在几分钟内发现了......

对于遇到与我相同问题的人来说,这是需要检查的。

出于某种原因(我现在不知道!)我改变了我的RouteConfig.cs文件以取出ID。所以我改变了这个:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

到 -

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{Id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );