如何在cshtml页面上显示来自HTTPHandler的响应

时间:2014-11-10 15:05:13

标签: c# asp.net razor

我有一个cshtml页面,其中包含一个将数据发送到HTTPHandler的表单。如果我遇到某种错误,我想回复一条错误消息,并将其显示在同一个cshtml页面中。我怎样才能做到这一点? 这是我的处理程序

public void ProcessRequest(HttpContext context)
{
    var mode = context.Request.Form["mode"];
    var title = context.Request.Form["postTitle"];
    var content = context.Request.Form["postContent"];
    var slug = context.Request.Form["postSlug"];
    var id = context.Request.Form["postId"];
    var datePublished = context.Request.Form["postDatePublished"];

    if (string.IsNullOrWhiteSpace(slug))
    {
        slug = CreateSlug(title);
    }

    if (mode == "edit")
    {
        EditPost(Convert.ToInt32(id), title, content, slug, datePublished, 1);
    }
    else if (mode == "new")
    {
        CreatePost(title, content, slug, datePublished, 1);
    }

    context.Response.Redirect("~/admin/post/");
}

private static void CreatePost(string title, string content, 
    string slug, string datePublished, int authorId)
{
    var result = PostRepository.Get(slug);
    DateTime? published = null;

    if (result != null)
    {
        throw new HttpException(409, "Slug is already in use.");
    }

    if (!string.IsNullOrWhiteSpace(datePublished))
    {
        published = DateTime.Parse(datePublished);
    }

    PostRepository.Add(title, content, slug, published, authorId);
}

private static void EditPost(int id, string title, string content,
    string slug, string datePublished, int authorId)
{
    var result = PostRepository.Get(id);
    DateTime? published = null;

    if (result == null)
    {
        throw new HttpException(404, "Post does not exist.");
    }

    if (!string.IsNullOrWhiteSpace(datePublished))
    {
        published = DateTime.Parse(datePublished);
    }

    PostRepository.Edit(id, title, content, slug, published, authorId);
}

private static string CreateSlug(string title)
{
    title = title.ToLowerInvariant().Replace(" ", "-");
    title = Regex.Replace(title, @"[^0-9a-z-]", string.Empty);

    return title;
}

这是cshtml文件中的表单

var post = Post.Current;

<div>
    <form name="post" method="post" action="~/admin/post.ashx">
        <input type="hidden" name="mode" value="@mode" />
        <input type="hidden" name="postId" value="@post.Id" />
        <p>Title: <input type="text" name="postTitle" value="@post.Title" /></p>
        <p>Content: <textarea name="postContent">@post.Content</textarea></p>
        <p>Slug: <input type="text" name="postSlug" value="@post.Slug" /></p>
        <p>Date Published: <input type="text" name="postDatePublished" value="@post.DatePublished" /></p>

        <p><input type="submit" name="postSubmit" value="Submit" /></p>

    </form>
</div>

例如:现在,如果帖子已经存在,我会抛出异常。我如何发送一条错误消息,上面写着&#34; Slug已经在使用&#34;然后将其显示在cshtml页面上,最好是在表单的顶部?感谢。

0 个答案:

没有答案