Search code examples
c#asp.net-mvcmodel-view-controllerentity-framework-coremulti-page-application

ASP.Net Buttons not linking to respective Views/Pages (local host error issued when selected)


I'm new to learning ASP.Net and currently working on a multi-page web app. My home view looks great but when I try to open up my "Add contact" view or my "Edit" or "Delete" views I get an error stating the local host page cannot be found. I'm having trouble pin pointing what my issues is- here is some code from my Index file and some from my controller files. Please let me know if I should be looking elsewhere.

Index File Code in relation to those views:

   <td>
            <a asp-controller="ContactInfo" asp-action="Edit" asp-route-id="@contact.ContactId" aps- 
   route-slug="contact.Slug">Edit</a>
            <a asp-controller="ContactInfo" asp-action="Delete" asp-route-id="@contact.ContactId" 
    aps-route-slug="contact.Slug">Delete</a>
        </td>
    </tr>

Home Controller Code:

         public class HomeController : Controller
    {
        private ContactContext context { get; set; }

        public HomeController(ContactContext ctx)
        {
            context = ctx;
        }

        public IActionResult Index()
        {
            var contacts = context.Contacts.OrderBy(m => m.Name).ToList();
            return View(contacts);
        }
    }

Contact List Controller Code:

   public class ContactListController : Controller
{
    private ContactContext context { get; set; }

    public ContactListController(ContactContext ctx)
    {
        context = ctx;
    }

    [HttpGet]
    public IActionResult Add()
    {
        ViewBag.Action = "Add";
        return View("Edit", new ContactInfo());
    }

    [HttpGet]
    public IActionResult Edit(int id)
    {
        ViewBag.Action = "Edit";
        var contact = context.Contacts.Find(id);
        return View(contact);
    }

    [HttpPost]
    public IActionResult Edit(ContactInfo contact)
    {
        if (ModelState.IsValid)
        {
            if (contact.ContactId == 0)
                context.Contacts.Add(contact);
            else
                context.Contacts.Update(contact);
            context.SaveChanges();
            return RedirectToAction("Index", "Home");

        }
        else
        {
            ViewBag.Action = (contact.ContactId == 0) ? "Add" : "Edit";
            return View(contact);
        }
    }
    [HttpGet]
    public IActionResult Delete(int id)
    {
        var contact = context.Contacts.Find(id);
        return View(contact);
    }
    [HttpPost]
    public IActionResult Delete(ContactInfo contact)
    {
        context.Contacts.Remove(contact);
        context.SaveChanges();
        return RedirectToAction("Index", "Home");
    }
}

Solution

  • your controller's name is ContactList as i can see, but you inserted something else here asp-controller="ContactInfo", also i think route-slug="contact.Slug" is not needed.