HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Using AJAX to interact with MVC

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ajaxmvcinteractwithusing

Problem

I have the following ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'json',
        data: 'source=' + $('#markItUp').val(),
        success: function (data) {
            $('#previewMode').html(data.RenderedSource);
        }
    });
};


Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Json(new { RenderedSource = m_wikiEngine.Render(source, GetRenderers()) });
}


And modal window:

I can switch between the design and preview tabs instantly which allows me to make changes in "Design Mode" and then instantly preview the effect of those changes before saving it to the Wiki. This works as I expect it to but I suspect that A. somehow I can accomplish this with get instead of post and B. I might not be going about this the right way.

Sure, it works exactly as I want it to but this is my first real web app and I'm confident that I'm "doing things right" here.

Solution

Well there's not much code to review here, but for what's here, I'd say it looks okay. I would only make one suggestion. If all you're going to do in your controller action is return single string wrapped up in a JSON object, why not dispose of the JSON and just return the HTML as content?

Ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'html',
        data: 'source=' + $('#markItUp').val(),
        success: function (result) {
            $('#previewMode').html(result);
        }
    });
};


Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Content(m_wikiEngine.Render(source, GetRenderers()));
}

Code Snippets

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'html',
        data: 'source=' + $('#markItUp').val(),
        success: function (result) {
            $('#previewMode').html(result);
        }
    });
};
[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Content(m_wikiEngine.Render(source, GetRenderers()));
}

Context

StackExchange Code Review Q#27245, answer score: 4

Revisions (0)

No revisions yet.