如何将对象传递到包含.NetCore

时间:2019-04-22 22:32:37

标签: c# ajax asp.net-core

我有一个要传递给控制器​​的对象。该对象包含多个字符串,这些字符串包含html代码的不同部分。我的代码适用于传递正常的字符串,但是一旦我尝试添加html代码,它就无法继续路由,我开始获取404。

我尝试更改模型以在传递字符串之前对字符串进行编码,但是完全失败了。如果3个字符串中不包含html代码,则以下代码有效。我正在尝试通过ajax调用将示例字符串传递给控制器​​。

JavaScript

var htmlString1 = '<div style="width: 100px;">Test html div 1</div>';
var htmlString2 = '<div style="width: 100px;">Test html div 2</div>';
var htmlString3 = '<div style="width: 100px;">Test html div 3</div>';

var htmlSectionContainer = {
    htmlSection1: htmlString1,
    htmlSection2: htmlString2,
    htmlSection3: htmlString3
};

debugger;
$.ajax({
    url: "@Url.Action("DisplayHtmlObjects", "Pages")",
    method: "GET",
    data: { "data": JSON.stringify(data) },
    success: (response) => {
        //do things
    });
}

型号

public class HtmlSectionContainer
{
    //Article ids for each of the pivot section intros.
    public string htmlSection1{ get; set; }
    public string htmlSection2 { get; set; }
    public string htmlSection3 { get; set; }
}

控制器动作

[HttpGet]
public IActionResult DisplayHtmlObjects(string data)
{
    HtmlSectionContainer section = new HtmlSectionContainer();

    if (data != null)
    {
        section = JsonConvert.DeserializeObject<HtmlSectionContainer>(data);
    }

    return View(section);
}

上述html字符串的实际结果是404。

尝试对对象内的各个字符串进行编码仍然会给我一个404。

var htmlSectionContainer = {
    htmlSection1: encodeURI(htmlString1),
    htmlSection2: encodeURI(htmlString2),
    htmlSection3: encodeURI(htmlString3)
};

现在我在控制器动作中根本没有碰到断点。我应该能够击中断点,并在data参数中看到3个字符串中的每一个。

如果可能的话,还进行一些细微的改进,我宁愿使用HtmlSectionContainer数据作为参数,而不是控制器操作中的字符串数据(当我尝试执行此操作时该数据为null)。

1 个答案:

答案 0 :(得分:0)

此JS代码中存在语法错误,我认为这是URL错误

$.ajax({
    url: "@Url.Action("DisplayHtmlObjects", "Pages"),
    method: "GET",
    data: { "data": JSON.stringify(data) },
    success: (response) => {
        //do things
    });
}

应该是这样,您错过了关闭“应该是这样

$.ajax({
    url: '@Url.Action("DisplayHtmlObjects", "Pages")',
    method: "GET",
    data: { "data": JSON.stringify(data) },
    success: (response) => {
        //do things
    });
}

我已在此行中将双引号“替换为单引号”

'@Url.Action("DisplayHtmlObjects", "Pages")'

因为在字符串中使用了双引号,这会使JS认为字符串已在此处结束。

同样,您正在传递data对象JSON.stringify(data),但我看不到该变量在何处声明和填充,您正在使用上面的变量htmlSectionContainer来设置HTML数据。所以我想应该是这样的。

$.ajax({
    url: '@Url.Action("DisplayHtmlObjects", "Pages")',
    method: "GET",
    data: { "data": JSON.stringify(htmlSectionContainer) },
    success: (response) => {
        //do things
    });
}