使用 ASP.net 进行 MVC 服务器端验证

发布于 2024-12-03 13:12:10 字数 2801 浏览 0 评论 0原文

我正在尝试在 MVC 网站中对文本框进行服务器端验证。这是我所拥有的:

   <% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get))
       {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
    <%=Html.Label("Please enter URL:") %>
    <%=Html.TextBox("url")%>
    <%= Html.ValidationMessage("url", "*") %>

    <input type="submit" value="Crawl" />

    </p>
    </fieldset>
    <% } %>

在控制器中我有这样的:

public ActionResult WebsiteLinks(string url)
        {
            if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"))
            {
                ViewData["AnchorText"] = url;
                return View(new Website(url, "Url"));
            }
            return RedirectToAction("Index");
        }

验证工作正常,但我想要实现的是,如果数据无效,如果数据不是正确的 url,我想重定向到相同的默认值页面上可能有一条消息: <%= Html.ValidationMessage("url", "*") %> 但我不知道该怎么做。

编辑

在完成下面建议的所有更改后,我在视图页面的标题中收到错误。我有 Inherits="ViewPageBase" ,其中 Home 是类的名称,Models 文件夹中的 Home.cs 。 在 home.cs 文件中,我有这个:

namespace LAX.Models
{
    public class UrlModel
    {
        [Required]
        [DisplayName("Please enter URL:")]
        [RegularExpression(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?")]
        public string Url { get; set; }
    }
}

在控制器中,我有:

   [HttpPost]
        public ActionResult WebsiteLinks(UrlModel model)
        {
            /*
            if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"))
            {
                ViewData["AnchorText"] = url;
                return View(new Website(url, "Url"));
            }
            else
            {
                ModelState.AddModelError("url", "Error URL Format");
            }
            return RedirectToAction("Index");
             */

            if (ModelState.IsValid)
            {
                ViewData["AnchorText"] = model.Url;
                return View(new Website(model.Url, "Url"));
            }
            return RedirectToAction("Index");

        }

在视图中,我有:

  <% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get))
       {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
        <%=Html.LabelFor(m => m.Url) %>
        <%=Html.TextBoxFor(m => m.Url) %>
        <%=Html.ValidationMessageFor(m => m.Url) %>

    <input type="submit" value="Crawl" />

    </p>
    </fieldset>
    <% } %>

这是错误:“无法找到类型或命名空间名称“Home”(您是否缺少 using 指令或装配参考?)”

I am trying to put server side validation for a textbox in MVC website. Here is what I have:

   <% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get))
       {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
    <%=Html.Label("Please enter URL:") %>
    <%=Html.TextBox("url")%>
    <%= Html.ValidationMessage("url", "*") %>

    <input type="submit" value="Crawl" />

    </p>
    </fieldset>
    <% } %>

And in the controller I have this:

public ActionResult WebsiteLinks(string url)
        {
            if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
            {
                ViewData["AnchorText"] = url;
                return View(new Website(url, "Url"));
            }
            return RedirectToAction("Index");
        }

The validation is working fine, but what I want to achieve is if the data is not valid, if the data is not proper url, I want to redirect to the same default page with a message probably here: <%= Html.ValidationMessage("url", "*") %> but I don't know how to do that.

Edit

After I did all the changes recommended below, I am getting an error in the header of the view page. I have Inherits="ViewPageBase<Home>" where Home is the name of the class, Home.cs in the Models folder.
In the home.cs file I have this:

namespace LAX.Models
{
    public class UrlModel
    {
        [Required]
        [DisplayName("Please enter URL:")]
        [RegularExpression(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?")]
        public string Url { get; set; }
    }
}

in the controller I have:

   [HttpPost]
        public ActionResult WebsiteLinks(UrlModel model)
        {
            /*
            if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
            {
                ViewData["AnchorText"] = url;
                return View(new Website(url, "Url"));
            }
            else
            {
                ModelState.AddModelError("url", "Error URL Format");
            }
            return RedirectToAction("Index");
             */

            if (ModelState.IsValid)
            {
                ViewData["AnchorText"] = model.Url;
                return View(new Website(model.Url, "Url"));
            }
            return RedirectToAction("Index");

        }

and in the view I have:

  <% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get))
       {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
        <%=Html.LabelFor(m => m.Url) %>
        <%=Html.TextBoxFor(m => m.Url) %>
        <%=Html.ValidationMessageFor(m => m.Url) %>

    <input type="submit" value="Crawl" />

    </p>
    </fieldset>
    <% } %>

Here is the error: "The type or namespace name 'Home' could not be found (are you missing a using directive or an assembly reference?)"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靑春怀旧 2024-12-10 13:12:10
public ActionResult WebsiteLinks(string url)
{
    if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
    {
        ViewData["AnchorText"] = url;
        return View(new Website(url, "Url"));
    }
    else
    {    
        ModelState.AddModelError("url", "*");
    }

    return RedirectToAction("Index");
}

或者你可以使用DataAnnotationsModel和强类型View

Model:

public class UrlModel
{
    [Required]
    [DisplayName("Please enter URL:")]
    [RegularExpression(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?")]
    public string Url { get; set; }
}

Controller 使这个更性感:

public ActionResult WebsiteLinks(UrlModel model)
{
    if (ModelState.IsValid)
    {
        ViewData["AnchorText"] = model.Url;
        return View(new Website(model.Url, "Url"));
    }
    return RedirectToAction("Index");
}

查看:

<%@ Page Language="C#" Inherits="ViewPageBase<UrlModel>" %>
<% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get)) {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
        <%=Html.LabelFor(m => m.Url) %>
        <%=Html.TextBoxFor(m => m.Url) %>
        <%=Html.ValidationMessageFor(m => m.Url) %>

        <input type="submit" value="Crawl" />
    </p>
</fieldset>
<% } %>
public ActionResult WebsiteLinks(string url)
{
    if (Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
    {
        ViewData["AnchorText"] = url;
        return View(new Website(url, "Url"));
    }
    else
    {    
        ModelState.AddModelError("url", "*");
    }

    return RedirectToAction("Index");
}

or you can make this sexier with DataAnnotations, Model, and a strongly typed View

Model:

public class UrlModel
{
    [Required]
    [DisplayName("Please enter URL:")]
    [RegularExpression(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?")]
    public string Url { get; set; }
}

Controller:

public ActionResult WebsiteLinks(UrlModel model)
{
    if (ModelState.IsValid)
    {
        ViewData["AnchorText"] = model.Url;
        return View(new Website(model.Url, "Url"));
    }
    return RedirectToAction("Index");
}

View:

<%@ Page Language="C#" Inherits="ViewPageBase<UrlModel>" %>
<% using (Html.BeginForm("WebsiteLinks", "Home", FormMethod.Get)) {%>   
    <%: Html.ValidationSummary("Please enter valid URL and try again.") %>
    <fieldset>
    <p>
        <%=Html.LabelFor(m => m.Url) %>
        <%=Html.TextBoxFor(m => m.Url) %>
        <%=Html.ValidationMessageFor(m => m.Url) %>

        <input type="submit" value="Crawl" />
    </p>
</fieldset>
<% } %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文