[RESOLVED]How to display the response from an HTTPHandler on a cshtml page

Hello,

I have a cshtml page that has a form which sends data to an HTTPHandler. If I run into some kind of error I want to respond with an error message and display it in the same cshtml page. How can I do this? Here is my handler

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;
}

And here is the form in the cshtml file

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>

For example: Right now I’m throwing an exception if the post slug already exists. How would I send an error message that says "Slug is already in use" and then display it on the cshtml page preferably right on top of the form? Thanks.

The problem you always have when posting to a different end point is preserving form values. One way to circumvent that issue is to use AJAX to detect if the slug is already in use and prevent form submission.

Hi Mike,

Thanks for the reply. I’m very new to ASP.NET. In fact, I just recently finished reading your book and now I’m trying to build a simple CMS following some other tutorials. Are there any resources you can point me to that would teach me how to do what you
mentioned?

If you are only just starting, I would suggest not using HttpHandlers for processing the form. You should post the form to the same page and process it in a code block at the top. There is no reason why you cannot put your methods into classes in App_Code
and call them from the code block at the top of the page. At least that way, the posted values are still available for re-display if there are validation errors.

For your specific requirement, you can add a separate cshtml file with this in it:

Json.Write(PostRepository.Get(Request["postSlug"]) != null);

Then you can call that via AJAX (using jQuery):

$('#postSlug').on('change', function () {
    $.getJSON('/CheckSlug?name=' + $(this).val(), function (data) {
        if (data) {
            // the slug exists
         };
     });
});

I use something similar in my CMS: https://webpagescms.codeplex.com/SourceControl/latest#WebPagesCMS/Admin/Widgets/AddHtmlWidget.cshtml

Leave a Reply