如何使用按钮(提交)从视图调用actionresult?

时间:2019-02-07 11:04:31

标签: c# asp.net-mvc

我正在尝试在控制器中调用actionresult。但是它不是从视图中调用它的。

我尝试使用onclick="location.href='@Url.Action("action", "controller")'">,但它甚至都没有输入该功能。

我的观点:

@using (Html.BeginForm("WritePost", "Post", FormMethod.Post, new { enctype 
= "Multipart/form-data" }))
{

@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Skriv inlägg</h4>
<hr />
<div>
@{Html.RenderAction("_CategoryPartialView", "Category");}
@Html.HiddenFor(model => model.CategoryId)
</div>

<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = 
"control-label col-md-2" })
<div class="col-md-10">
    @Html.EditorFor(model => model.Title, new { htmlAttributes = new { 
@class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Title, "", new { @class = 
"text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = 
"control-label col-md-2" })
<div class="col-md-10">
    @Html.TextAreaFor(model => model.Content, 10, 100, new { @class = 
"form-control" })
    @Html.ValidationMessageFor(model => model.Content, "", new { @class = 
"text-danger" })
</div>

<input type="file" name="file" />
@Html.ValidationMessageFor(model => model.File)

</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Send" class="btn btn-default" />

我的控制器

public ActionResult EmailWhenPost()
{
    try
    {
        if (ModelState.IsValid)
        {
            var senderEmail = new MailAddress("ExampleMail@gmail.com");
            var receiverEmail = new MailAddress("ExampleMail2@gmail.com");
            var password = "Pass";
            var subject = "New Post";
            var body = "Message";
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(senderEmail.Address, password)
            };
            using (var mess = new MailMessage(senderEmail, receiverEmail)
            {
                Subject = subject,
                Body = body
            })
            {

                smtp.Send(mess);
            }
            return View();
        }
    }

    catch (Exception)
    {
        ViewBag.Error = "Some Error";
    }
    return View();
}

我想使用该功能在发送帖子时发送电子邮件。它不应该返回视图,而只是触发该函数。

1 个答案:

答案 0 :(得分:0)

您应该调用正确的函数MyController / EmailWhenPost(请将其重命名为SendEmail,并添加[HttpPost]的属性,然后在控制器操作中仅返回void(返回void的控制器方法将产生EmptyResult。)< / p>

W3C specification

First read this article about general rounting in ASP.NET MVC