【问题标题】:Pass objects from JS to controller and razor mail template将对象从 JS 传递到控制器和 razor 邮件模板
【发布时间】:2018-06-16 09:20:49
【问题描述】:

我一直在尝试将邮件功能从 2sxc mobius 应用程序中分离出来,以便在我自己的 2sxc 项目中实现它,但到目前为止,我只成功地传递了字符串、字符串字典。如果我尝试使用默认字符串,对象它会给出几个编译不是很具体的错误。

这是我现在的工作:

查看:

<div>
    <div>
        <label for="testfield">Test field</label>
    </div>
    <div>
        <input type="text" id="testfield" value="">
    </div>
</div>

<div>
    <button id="saveData" type="button" onclick="saveMailData()">Guardar dados</button>
</div>

<script type="text/javascript" src="/desktopmodules/tosic_sexycontent/js/2sxc.api.min.js" data-enableoptimizations="100"></script>

<script>
function saveMailData() {

    var newItem = {
        "user": "@Dnn.User.Username",
        "testfield": $("#testfield").val()
    };

    $2sxc(@Dnn.Module.ModuleID).webApi.post("Form/ProcessForm", {}, newItem, true)
    .success(function() {
        alert("Success");
    })
    .error(function() {
        alert("Error");
    });
}
</script>

控制器:

using DotNetNuke.Security;
using DotNetNuke.Web.Api;
using System.Web.Http;
using ToSic.SexyContent.WebApi;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web.Compilation;
using System.Runtime.CompilerServices;
using DotNetNuke.Services.Mail;
using Newtonsoft.Json;

public class FormController : SxcApiController
{

    [HttpPost]
    [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Anonymous)]
    [ValidateAntiForgeryToken]
    public void ProcessForm([FromBody]Dictionary<string,string> contactFormRequest)
    {

    string mailFrom = "x@x.pt";
    string mailTo = "y@y.com";
    string mailCc = "z@z.com";
    string mailReply = "w@w.pt";
    string mailSubject = "THIS IS THE SUBJECT " + contactFormRequest["user"].ToString();
    string mailbody = "<table><tr><td>THIS IS THE MESSAGE BODY</td></tr></table>";

    var ownerMailEngine = TemplateInstance("testmailtemplate.cshtml");
    var ownerBody = ownerMailEngine.Message(contactFormRequest, this).ToString();
    var ownerSubj = ownerMailEngine.Subject(contactFormRequest, this);

    Mail.SendMail(mailFrom, mailTo, mailCc, "", mailReply, MailPriority.Normal, ownerSubj, MailFormat.Html, System.Text.Encoding.UTF8, ownerBody, new string[0], "", "", "", "", false);
    }

    private dynamic TemplateInstance(string fileName)
    {
        var compiledType = BuildManager.GetCompiledType(System.IO.Path.Combine("~", App.Path, fileName));
        object objectValue = null;
        if (compiledType != null)
        {
            objectValue = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType));
            return ((dynamic)objectValue);
        }
        throw new Exception("Error while creating mail template instance.");
    }
}

和模板:

@helper Message(Dictionary<string,string> request, ToSic.SexyContent.IAppAndDataHelpers context)
{
    <!doctype html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            body { font-family: Helvetica, sans-serif; }
        </style>
    </head>
    <body>
        <h1>Website contact form request</h1>
        <p>Key/Value:</p>
        <table width="100%">
            @foreach (var item in request)
            {
                <tr>
                    <td width="10%"><b>@item.Key.ToString()</b></td>
                    <td>@item.Value.ToString()</td>
                </tr>
            }
        </table>
    </body>
</html>
}

@functions {
    public string Subject(dynamic request, dynamic helpers) {
        return "this is a subject from template";
    }
}

我真的很想避免使用动态来接收数据(这对初学者来说是一场噩梦),所以你能帮我正确地将数据作为对象(字符串、对象)从 JS 传递到控制器,从控制器传递到 razor 模板吗?

【问题讨论】:

    标签: javascript c# razor 2sxc


    【解决方案1】:

    如果您尝试使用,您会以某种方式假设系统会正确地将这些转换为数字、日期等。这通常是不可靠的并且会导致很多副作用。例如,输入字段中的数字将是浏览器中的字符串,因此它也将作为字符串到达​​服务器中。

    日期会更糟:它们将被视为字符串 - 并且没有自动检测会将它们转换为日期,因为 AJAX 调用使用的 JSON 格式没有日期标准。

    因此,如果您尝试使用对象方法,基本上数字和日期都不会给您带来任何好处(因为它不会自动具有其他类型)。所以我不确定是否有任何额外的好处。还有其他理由这样做吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2021-01-07
      • 2015-12-10
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多