0

Question:
What's the best way to pass JSON data in javascript to an ASP.NET MVC strongly typed partial view?

Details:
I'm developing on a Win7 machine using VS2013 Express for Web.
I have a strongly-typed partial view using a class Workorder:

@model WebApplication1.Models.WorkOrder.WorkOrder
<h3>Partial Result:</h3>
Name: @Model.woName
<br />
SN: @Model.woSN
<br />

I make an AJAX call in my javascript on a Razor view page, that returns JSON data called "data":

function showPartial(data) {
    @{
        WorkOrder w = Json.Decode(<text>data</text>, WorkOrder);
        @Html.Partial("PartialWOTop", w);
    }
}

However, the view page won't process properly. I get the following error:

 Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1525: Invalid expression term '<'

Source Error:


Line 36:         function showPartial(data) {
Line 37:             @{
Line 38:                 WorkOrder y = Json.Decode(<text>data</text>, WorkOrder);
Line 39:                 @Html.Partial("PartialWOTop", y);
Line 40:             }


Source File: c:\Users\xupd48act\Documents\Computer\Dev\VS Projects\WebApplication1\WebApplication1\Views\BacklogTracker\Index.cshtml    Line: 38 
1
  • The first parameter to Json.Decode() should be a JSON string, but your example has (unquoted) XML ... am I missing something? Commented Dec 30, 2014 at 20:29

1 Answer 1

2

You are trying to inject client-side code into the server-side generation of the partial view. That is not the way MVC partial views work. The partial view is already rendered before the page is supplied to the browser (i.e. long before the client side jQuery is run).

Instead you need to POST/GET the data to a controller method, return your partial view based on that data, and then render the returned HTML by inserting it into your page.

e.g. something like this:

function showPartial(data) {
    $.ajax({
       url: "controller/action",
       data: data,
       dataType: html,    // Expect back HTML
       success: function(html){
           $('#someelement').html(html);
       }
    });
}

or the shorter version using $.load:

function showPartial(data) {
    $('#someelement').load( "controller/action", data );
}

The server-side MVC controller method needs to take the data and return a partial view (as it probably does now). You need to show your controller code if you need more details :)

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh yes okay that explains it for a newbie. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.