如何从控制器发送短信或 link 以查看?
How to send a text message or a link from controller to view?
我有一个表单的提交按钮,按下按钮时将调用此控制器 actionresult 方法。取决于_shortUrlProcessor.CreateShortURL
方法的return。我想以红色显示一条消息或在提到的提交按钮下创建一个 link。在 MVC 中处理这个问题的正确方法是什么? (也请参阅代码中的注释以获得更多说明)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ShortenURL(ShortURLModel model)
{
if(ModelState.IsValid)
{
if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
{
ViewBag.ShortenURLSuccess(model.shortURL); //< ---- send as a localhost:port/model.shortURL link
}
else
{
ViewBag.ShortenURLSuccess("Could not create link"); //<----send as a text label (which would be shown in something like a <div/>)
}
}
return View();
}
将它放在视图中是可行的方法,下面是一个使用 viewbag 方法的示例:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ShortenURL(ShortURLModel model)
{
if(ModelState.IsValid)
{
if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
{
ViewBag.ShortenURLSuccess=true;
ViewBag.ShortenURL=model.shortURL;
}
else
{
ViewBag.ShortenURLSuccess=false;
}
}
return View();
}
然后在视图中:
@if (ViewBag.ShortenURLSuccess)
{
<a href="localhost:port/@ViewBag.ShortenURL">Go here</a>
}
else
{
<div class="error">Could not create link</div>
}
如果您需要有关 url 或消息的更多信息,您也可以将它们放入 viewbag 变量中。
值得注意的是,更流行的方法是使用模型绑定,但这种方法效果很好。您可以使用提交的模型并远离 viewbag 以提高效率。
我有一个表单的提交按钮,按下按钮时将调用此控制器 actionresult 方法。取决于_shortUrlProcessor.CreateShortURL
方法的return。我想以红色显示一条消息或在提到的提交按钮下创建一个 link。在 MVC 中处理这个问题的正确方法是什么? (也请参阅代码中的注释以获得更多说明)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ShortenURL(ShortURLModel model)
{
if(ModelState.IsValid)
{
if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
{
ViewBag.ShortenURLSuccess(model.shortURL); //< ---- send as a localhost:port/model.shortURL link
}
else
{
ViewBag.ShortenURLSuccess("Could not create link"); //<----send as a text label (which would be shown in something like a <div/>)
}
}
return View();
}
将它放在视图中是可行的方法,下面是一个使用 viewbag 方法的示例:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ShortenURL(ShortURLModel model)
{
if(ModelState.IsValid)
{
if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
{
ViewBag.ShortenURLSuccess=true;
ViewBag.ShortenURL=model.shortURL;
}
else
{
ViewBag.ShortenURLSuccess=false;
}
}
return View();
}
然后在视图中:
@if (ViewBag.ShortenURLSuccess)
{
<a href="localhost:port/@ViewBag.ShortenURL">Go here</a>
}
else
{
<div class="error">Could not create link</div>
}
如果您需要有关 url 或消息的更多信息,您也可以将它们放入 viewbag 变量中。
值得注意的是,更流行的方法是使用模型绑定,但这种方法效果很好。您可以使用提交的模型并远离 viewbag 以提高效率。