使用MVC Razor View发送电子邮件

时间:2013-08-06 14:19:47

标签: c# asp.net-mvc razor

我是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. 我想在文本框中应用样式&amp; sendmail链接。我应该如何使用这些类型的控件?

  3. @ Html.TextBoxFor(m =&gt; m.EmailID)

    1. 我是否遵循MVC标准?如果不是,那么。

2 个答案:

答案 0 :(得分:4)

  1. 在您的视图中,您不需要RenderAction调用,但需要将正确的操作传递给初始窗体

  2. 应用样式:您可以使用所需的属性传递动态对象。在这种情况下,我添加了一个class-attrbute(然后你必须使用CSS设置样式)

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

答案 1 :(得分:3)

你不需要这个:

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

}

只需将BeginForm方法更改为:

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

这会强制submit按钮POST到您在控制器中描述的方法。它将控制器名称PagesPagesController匹配,然后匹配操作名称方法类型相匹配,并找到:

[HttpPost]
public ActionResult SendMail ...

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

form input[type="text"] {

}
例如,

设置text输入的样式。