Home > front end >  See ASP.NET MVC Index page in C# be populated with data from model without ID in the URL
See ASP.NET MVC Index page in C# be populated with data from model without ID in the URL

Time:09-21

In my application I am using Entity Framework 6 and ASP.NET MVC in C#.

I have a table that has records that I plan on populating my Index page with. How do I populate the index page without having the system add the id of the record to the URL. See example below. I have already looked at routing but with adding custom route you are forced to add more text to the url when all I want is the URL to show up as example.com. I don't want and don't need example.com/MenuRecords/Details/20 for a user to see.

So example.com should load the following data from the model below in the index view of the HomeController.

index.cshtml page calling the model data shown below:

@model example.Models.tblMenuRecords

@Model.ThisWeeksBestDrink
@Model.ThisWeeksBestAppetizer
@Model.ThisWeeksBestDesert
@Model.ThisWeeksBestLunchSpecial

This is the cntroller action method:

public ActionResult Index()
{
    return View();
}

How do I get that to work properly for the Index page? Since this is the home page that is calling data from a model I cannot have the URL have anything other than example.com .... but I do understand that when calling data from a model you do need some sort of ID but I just do not really understand how to do that.

I know that there is the route config that includes this default route that allows you to show only the name of the domain...But how is this done when you are trying to load data from the database.

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Is this the correct way to pass an instance of the tblMenuRecords to the view?

public ActionResult Index()
{
    tblMenuRecords tblMenuRecords = db.tblMenuRecords();

    return View(tblMenuRecords);
}

CodePudding user response:

        I think your view is missed with model. View code should be like below
        @model Models.MenuRecords
        @{
            ViewBag.Title = "Menu Records";
        }
        
        <h2>Details</h2>
        
        <div>
            <h4>Menus</h4>
        <hr />
        <table>
            <tr>
                <td>
                    @Html.DisplayFor(model => model.ThisWeeksBestDrink)
                </td>
                 <td>
     @Html.DisplayFor(model => model.ThisWeeksBestLunchSpecial)
       </td>
            </tr>
        </table>
        </div>
I hope, it will help you. 

CodePudding user response:

I think you have to fix the action

public ActionResult Index()
{
    tblMenuRecords tblMenuRecords = db.tblMenuRecords.FirstOrDefault();

    return View(tblMenuRecords);
}
  • Related