简体   繁体   English

将对象从JS传递到控制器和剃须刀邮件模板

[英]Pass objects from JS to controller and razor mail template

I've been trying to isolate the mail feature from 2sxc mobius app to implement it on my own 2sxc projects, but so far I've only been successful on passing string, string dictionary. 我一直在尝试从2sxc mobius应用程序中隔离邮件功能,以在我自己的2sxc项目中实施该功能,但到目前为止,我仅在传递字符串,字符串字典方面取得了成功。 If I try to use the default string,object it gives several compiling not very specific errors. 如果我尝试使用默认字符串object,它会给出几个编译错误,但不是非常具体的错误。

Here's what I have working right now: 这是我现在正在工作的内容:

View: 视图:

<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>

Controller: 控制器:

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.");
    }
}

And template: 和模板:

@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";
    }
}

I would really like to avoid using dynamic to receive data (it's a nightmare for beginners), so can you help me to properly pass data as objects (string,object) from JS to controller and from controller to razor template? 我真的想避免使用动态方式来接收数据(对于初学者来说这是一场噩梦),那么您能否帮助我正确地将数据作为对象(字符串,对象)从JS传递到控制器以及从控制器传递到剃刀模板?

If you try to use you'll somehow assume that the system will correctly convert these to number, date and so forth. 如果您尝试使用,您将以某种方式假定系统将它们正确地转换为数字,日期等。 This will usually not be reliable and cause a lot of side-effects. 这通常是不可靠的,并且会引起很多副作用。 For example, a number from an input-field would be a string in the browser, so it would also arrive as a string in the server. 例如,输入字段中的数字在浏览器中将是字符串,因此在服务器中也将以字符串形式到达。

Dates would be worse: they would be treated as strings - and no automatic detection would turn them into dates, because the JSON format used by AJAX-calls has no standard for dates. 日期会更糟:它们将被视为字符串-并且不会自动检测将它们转换为日期,因为AJAX调用使用的JSON格式没有日期标准。

So basically both numbers and dates would give you no benefit if you tried an object approach (as it wouldn't automatically have the other type). 因此,如果您尝试使用对象方法,则数字和日期基本上都不会给您带来任何好处(因为它不会自动具有其他类型)。 So I'm not sure if there is any additional benefit. 因此,我不确定是否还有其他好处。 Is there another reason to do this? 还有其他理由吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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