我正在做一个ASP.NET核心邮件函数,在这个过程中,我向我的HomeController提交了一个发送邮件并返回视图的表单。我被重定向到视图,有没有办法留在同一页而不是在localhost/Home/View中寻找视图?这是我的控制器:
[Route("api/[controller]")]
[ApiController]
public class HomeController : Controller
{
private readonly IMailService mailService;
private readonly ILogger<HomeController> _logger;
private readonly IToastNotification _toastNotification;
public HomeController(IMailService mailService,
ILogger<HomeController> logger,
IToastNotification toastNotification)
{
_logger = logger;
_toastNotification = toastNotification;
this.mailService = mailService;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> SendMail([FromForm] MailTemplate request)
{
try
{
await mailService.SendEmailAsync(request);
_toastNotification.AddSuccessToastMessage("Message Sent Successfully");
return View();
}
catch (Exception ex)
{
throw ex;
}
}
}
以下是我的启动终结点:
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}");
事前谢谢!
最好的问候Max
发布于 2021-03-18 06:11:59
你可以使用像NToastNotify
这样的库。
安装程序包
Install-Package NToastNotify
并在startup.cs中进行配置
services.AddControllersWithViews().AddNToastNotifyNoty();
app.UseNToastNotify();
在_Layout页面中添加以下内容:
@await Component.InvokeAsync("NToastNotify")
向HomeController注入依赖项IToastNotification
private readonly ILogger<HomeController> _logger;
private readonly IToastNotification _toastNotification;
public HomeController(ILogger<HomeController> logger, IToastNotification toastNotification)
{
_logger = logger;
_toastNotification = toastNotification;
}
然后在表单post操作中添加消息,并返回到当前视图。
[HttpPost]
public IActionResult Index(string emailAddress)
{
_toastNotification.AddSuccessToastMessage("Message Sent Successfully");
return View();
}
发布于 2021-03-18 06:29:18
您可以在HomeController
中使用Jquery和Ajax
public JsonResult SendEmail(string address,string content)
{
bool response;
//send email
return Json(response);
}
在View
中
var url = '@Url.Action("SendEmail", "Home")'
$.ajax({
url: url,
data: { address: $("#addresstextboxid").val(),content:$("#hometextboxid").val()},
success: function (response) {
// Whatever you want to do with response
}
});
https://stackoverflow.com/questions/66680692
复制相似问题