简体   繁体   中英

C# MVC 4 RAZOR - JSON return List from Controller to View using @foreach

I am new in MVC 4 Razor as I am going deeper into it I am thinking that, is it possible to pass a JSON list in ActionResult to View?

Here is my code in Controller:

public ActionResult Index()
{
    User _user = db.Users.ToList();
    return Json(_user , JsonRequestBehavior.AllowGet);
}

Here is my code in View: I want to place my JSON in @foreach

@model IEnumerable<MVC_AjaxActionLink.Models.User>
    <body>
        <input id="txtUser_Idx" type="text" />
        <input id="btnSend" name="btnSend" type="button" value="Search" />
        <div id="User_Result">
            @foreach (var item in Model)
            {
                <table>
                    <tr>
                        @Html.HiddenFor(modelItem => item.User_Idx)
                        <td>@Html.DisplayFor(modelItem => item.LoginName)</td>
                        <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                        <td>@Html.DisplayFor(modelItem => item.MiddleInitial</td>
                        <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                    </tr>
                </table>
            }
        </div>
    </body>

Here is my SQL table:

USE [Sample_db]
GO

CREATE TABLE [dbo].[Users](
    [User_Idx] [bigint] IDENTITY(1,1) NOT NULL,
    [LoginName] [nvarchar](20) NOT NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [MiddleInitial] [nvarchar](10) NULL,
    [LastName] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [User_Idx] ASC
))

GO

You're mixing two divergent technologies here. Json over Ajax and Razor. You can't bind a Json model object to a razor view. It doesn't work that way. If you want to use server side rendering with razor then you pass the model object to your view.

so

public ActionResult Index()
{
    User _user = db.Users.ToList();
    return Json(_user , JsonRequestBehavior.AllowGet);
}

should be changed to this (assuming your razor view is Index.cshtml):

public ActionResult Index()
{
    User _user = db.Users.ToList();
    return View(_user);
}

and on a side note, I would recommend using _users in your controller not user because you're really returning a collection of users not a single user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM