使用MVC 4在View的foreach循环中不生成HTML

时间:2014-06-06 15:51:12

标签: asp.net ajax asp.net-mvc

我使用AJAX调用ActionResult并返回文件列表。数据存储在模型中的字典对象中,然后传递给视图。我在视图中有一个foreach循环,它检查对象是否为null。如果没有,它循环遍历字典并为每个键/值对生成表行。问题是,HTML永远不会生成,也不会显示任何内容。使用Firebug我已经完成了整个过程,所有内容都按原样返回。任何帮助找出原因将不胜感激。

AJAX:

function () {
$.ajax({
    url: '@Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
    type: "GET",
    async: true,
    cache: false,
    data: { DirectoryName: "ER_#=EPR_ID#" },
    success: function() {
        alert("success!");
    },
    error: function(errorThrown) {
        console.log(errorThrown);
    }
});

}

控制器:

public ActionResult GetExpenseReportUploads(string DirectoryName)
    {
        ExpenseReport.MVC.Models.MyExpenseReports model = new MyExpenseReports();

        IEnumerable<string> fileArray = Directory.EnumerateFiles(Server.MapPath("~/Files/" + DirectoryName + "/")).Select(fn => "~/Files/" + DirectoryName + "/" + Path.GetFileName(fn));
        //model.EPR_Uploads = Path.GetFileName(fileArray);

        Dictionary<string, string> fileNames = new Dictionary<string, string>();

        foreach (string filePath in fileArray)
        {
            string fileName = Path.GetFileName(filePath);

            fileNames.Add(filePath, fileName);

            model.EPR_Uploads = fileNames;
        }

        model.EPR_Upload_DirectoryName = DirectoryName;

        return View(model);
    }

观点:

<table>
@if (Model.EPR_Uploads != null)
{
    foreach (KeyValuePair<string, string> upload in Model.EPR_Uploads)
    {
        <tr>
            <td>                                        
                @using (Html.BeginForm("DeleteUpload", "MyExpenseReports", FormMethod.Post))
                {
                    @Html.HiddenFor(m => m.FileId, new { @value = @upload.Value })
                    @Html.HiddenFor(m => m.EPR_Upload_DirectoryName)
                }
                <input type="submit" id="DeleteUploadBtn" value="Delete File" formaction="@Url.Action("DeleteUpload", "MyExpenseReports", new { FileId = @upload.Value, EPR_ID = "#=EPR_ID#", DirectoryName = Model.EPR_Upload_DirectoryName })" />
            </td>
            <td>

            </td>
            <td>

            </td>
        </tr>
    }
}                        

1 个答案:

答案 0 :(得分:0)

您正在混合服务器端处理和客户端处理。如果您希望在客户端AJAX调用之后构建表,则不要使用服务器端模型(Model.EPR_Uploads)。

相反,使用后加载客户端调用来构建HTML。例如:

function () {
$.ajax({
    url: '@Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
    type: "GET",
    async: true,
    cache: false,
    data: { DirectoryName: "ER_#=EPR_ID#" },
    success: function(data, textStatus, jqXHR) {
        $("#tableId").append("<tr><td>" + data.EPR_Upload_DirectoryName + "</td></tr>";
    },
    error: function(errorThrown) {
        console.log(errorThrown);
    }
});

您需要更改Controller以使用JSON返回数据,以便在客户端正确解析它。

希望这有帮助。