使用MVC Razor View发送电子邮件

本文关键字:电子邮件 View MVC Razor 使用 | 更新日期: 2023-09-27 18:26:34

我是MVC的初学者,必须在MVC应用程序中实现发送邮件的功能。

下面是我的代码。

视图:

@using (@Html.BeginForm())
{
@Html.TextBoxFor(m => m.EmailID)
<input type="submit" name="name" value="SendMail" />
@{ Html.RenderAction("SendMail", "PagesController");
}

控制器代码:PagesController

    [HttpPost]
    public ActionResult SendMail(EmailModel model)
    {
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("abc@abc.com");
        msg.To.Add(model.EmailID);
        msg.Subject = "Welcome To REBAR Mobile Showcase";
        msg.Body = "Hi," + Environment.NewLine + @"Welcome to REBAR Mobile Showcase. Please click on the below link : https://ciouishowcase.accenture.com/mobile/m"
            + Environment.NewLine + "Regards," + Environment.NewLine + "CIO Design Agency";
        msg.Priority = MailPriority.Normal;
        SmtpClient client = new SmtpClient();
        client.Credentials = new NetworkCredential("abc", "passwrod", "Dir");
        client.Host = "email.abc.com";
        client.Port = 587;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Send(msg);
        return View();
    }

型号:EmailModel

public class EmailModel
{
    public string EmailID { get; set; }
}

我有几个问题:

  1. 我应该如何在点击发送链接按钮时调用这个方法。

  2. 我想在文本框上也应用样式&sendmail链接。我应该如何使用这些类型的控件?

@Html.TextBoxFor(m=>m.EmailID)

  1. 我是否遵循MVC标准?如果没有,在哪里

使用MVC Razor View发送电子邮件

  1. 在您看来,您不需要RenderAction调用,但需要将正确的操作传递到起始表单

  2. 应用样式:可以传入具有所需元素属性的动态对象。在这种情况下,我添加了一个类属性(然后必须使用CSS对其进行样式设置)

    @using (@Html.BeginForm("SendMail", "Pages"))
    {    
        @Html.TextBoxFor(m => m.EmailID, new() {@class="somecssclass"})
        <input type="submit" name="name" value="SendMail" />
    }
    

您不需要这个:

@{ Html.RenderAction("SendMail", "PagesController");
}

只需将BeginForm方法更改为:

@Html.BeginForm("SendMail", "Pages", FormMethod.Post)

这将按照您在控制器中描述的方法将submit按钮强制设置为POST。它将控制器名称PagesPagesController相匹配,然后将操作名称与方法类型相匹配,并找到以下内容:

[HttpPost]
public ActionResult SendMail ...

至于应用样式,这是通过基本的HTML和CSS完成的。你可以使用类似的东西:

form input[type="text"] {
}

以对例如CCD_ 6输入进行样式化。