MVC 1.0 help, accessing View HTML

hi EE,
I am trying to send a JSON object back to my ajax javascript event.

In my controller im returning a Json object although I need to access the HTML of the view?  Is this possible?

see my attempt below.

Thanks,
public ActionResult test()
{
    HTML = View("myPage");  // this doesnt render the html into the HTML variable as I hoped! (?)
    return Json(new {html = HTML});
}


// in my javascript I can then go
$('theDIV').html = HTML;

Open in new window

jimbona27Asked:
Who is Participating?
 
jamesbaileConnect With a Mentor Commented:
You are on the right track and I'd suspect that it's to do with your javascript code.

Try separating out the second javascript call into a dfunction on it's own right and test that.

i.e.

function updateView(){
    $.ajax(
                {
                    type: "GET",
                    url: MyViewURL,
                    dataType: "json",
                    cache: false,
                    success: function(data) {
                        alert("");
                    },
                    error: function(reg, status, error) {
 
                    }
                });
}

You can then change your validation call to read something like

$.ajax(
    {
        type: "GET",
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            if (data.Message != '') {
                // handle error messages within form
            }
            else {
               // Make second ajax call - this happens once the first one has returned and you have checked there are no errors in your data object
               updateView();
             }
        },
        error: function(reg, status, error) {
            $("#errorMessage").html(data.Message);
        }
    });
0
 
jamesbaileCommented:
Is there a reason why you need to send HTML back to the page as a JSON object.

I'd do the following

public ActionResult test()
{
    return PartialView("PartialViewName");
}

and keep your java script as is.
0
 
jimbona27Author Commented:
just experimenting with this idea, is it possible to update a DIV with a view? see below?
thanks,


    function loadNextStep() {
        document.getElementById('myDiv').innerHTML = test();
    }
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
jamesbaileCommented:
Yes. I'd really recomend using JQuery in conjunction with PartialViews. It makes things much easier.

You can write a javascript snippet something like

$(".my-html-control-class").click(function(){
    $.ajax({
        url: "/MyController/PartialAction",
        sucess: function(data){
           $('.myDiv').html(data);
        }
    });

What this does is attach an "OnClick" event to any clickable html element which has a class of "my-html-control-class". Then when the user clicks on the control an ajax get is called on MyController and the resulting HTML is inserted into myDiv.


});


0
 
jimbona27Author Commented:
I have the following code.  I like what you're saying but it sounds like I have to make to ajax calls to the server?

one to perform the error check, and then another one, if no error to load the view!  is this correct?

thanks,
    $.ajax(
    {
        type: "GET",
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            if (data.Message != '') {
                // handle error messages within form
            }
            else {
                // ** load next step (ie. this is the part that needs to load the View) **
            }
        },
        error: function(reg, status, error) {
            $("#errorMessage").html(data.Message);
        }
    });

Open in new window

0
 
jimbona27Author Commented:
if this is the case, how can I call the view using ajax in this js method?
thanks,
0
 
jamesbaileCommented:
The JQuery error function happens when there is either a communication or unhandled server error. Therefore you can't do $("#errorMessage").html(data.Message); as there will be no message property of the data object.

In the else bit of your success function make a second ajax call to get the view

else {
    $.ajax({
        url: "/MyController/PartialAction",
        sucess: function(data){
           $('.myDiv').html(data);
        }
            }

and continue to handle the error messages within the form
0
 
jimbona27Author Commented:
sorry, how do you use $.ajax more than once in the code?
Thanks,
0
 
jamesbaileCommented:
$.ajax(
    {
        type: "GET",
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            if (data.Message != '') {
                // handle error messages within form
            }
            else {
               // Make second ajax call - this happens once the first one has returned and you have checked there are no errors in your data object
                $.ajax({
                       url: "/MyController/PartialAction",
                        sucess: function(data){
                       $('.myDiv').html(data);
                });
            }
        },
        error: function(reg, status, error) {
            $("#errorMessage").html(data.Message);
        }
    });
0
 
jimbona27Author Commented:
in the else clause i've tried this but although I see the new content within FF firefug the webpage doesnt change.

the alert() never happens??

Thanks
else {
                $.ajax(
                {
                    type: "GET",
                    url: MyViewURL,
                    dataType: "json",
                    cache: false,
                    success: function(data) {
                        alert("");
                    },
                    error: function(reg, status, error) {

                    }
                });

Open in new window

0
 
jimbona27Author Commented:
ignore my last question, fixed that bit.
0
 
jimbona27Author Commented:
the problem I've got is that when the form is complete I return a JSON object, i.e.

but when I return no errors I return a view like so:

return View("myview");  // instead of a JSON object


the problem is that in the ajax call I'm sayings its JSON so the error section works but when my validation passes it returns html, so it causes a JS runtime error (in FF firebug)

Any suggestions/ is that clear?

thanks,
$.ajax(
    {
        type: "POST",
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            $("#errorMessage").html(data.Message);
        },
        error: function(reg, status, error) {

        }
    });


//c#
return Json(new { Errors = errors, Message = message });

Open in new window

0
 
jimbona27Author Commented:
this property of the ajax call is causing the problem:

dataType: "json",


when the form validation has errors the info is returned as JSON, but when there's no errors it returns a view (i.e. dataType: "html")

is it possible to use another dataType or somehow convert between the two???

or is there a different/ better way?
Thanks,
0
 
jamesbaileCommented:
You can't mix and match JSON and HTML results.

To do what you want you need to make 2 ajax calls. The first sends the data you want validated and returns a JSON object with error messages, valid status etc. Then if the data is valid you make a second call to get the HTML for the partial view you want displayed. Your second call won't specify the returning data to be JSON (dataType: "json", )
0
 
jimbona27Author Commented:
ok, but when I check for whether to make another ajax call the check isnt working.

if(data.Message == '')
  alert(1);  // call view (using ajax)
else
  alert(2);  // handle JSON error


This is my logic to determine what to do but it always shows '2' but if I alert(data.Message) I get an empty alert..  is there another check I can do?

I've tried:

if(data.Message == null)
..

if(data.Message == '')
...


but they still trigger the FALSE clause...

is there another null method I can use???

Thanks
0
 
jimbona27Author Commented:
just tried if(data.Message.length > 0) and this works but I dont know why my other attempts failed...?

any ideas?
0
 
jamesbaileCommented:
Why not structure your JSON object so that it has an explicit IsValid property which is set by the controller?

if(data.isValid === true)
  alert(1);  // call view (using ajax)
else
  alert(2);  // handle JSON error

the === checks the existance of IsValid and that it's type matches on both sides.
0
 
jamesbaileCommented:
Also I'd highly recommend using FireFox and FireBug to debug client side. In the firebug console you can easily set a breakpoint and then enter data.Message == '' and variations to see what is causing the problem. You may find that if (data.Message) is all you need.
0
 
jimbona27Author Commented:
I have the following function that works in FF but when I use IE 8 the second AJAX call fails to display to the screen.
I can alert(data) and see the content I want but it doesnt render the markup in #abc.

any ideas why this would happen?
Thanks,



function mytest(url) {
    url = url + "xxx";

    $.ajax(
    {
        type: "GET",
        url: url,
        dataType: "json",
        cache: false,
        success: function(data) {
            
            if (data.Message != '') {
               ...
            }
            else {

                $.ajax(
                {
                    type: "GET",
                    url: xxx,
                    dataType: "html",
                    cache: false,
                    success: function(data) {                        
                        $('#abc').html(data);  // this line doesnt show the results in #abc -- but alert(data) shows the html I want to display ????
                    },
                    error: function(reg, status, error) {

                    }
                });


            }
        },
        error: function(reg, status, error) {
            $("#errorMessage").html(data.Message);
        }
    });
}

Open in new window

0
 
jimbona27Author Commented:
note: #abc does exist as a valid div panel.
0
 
jamesbaileCommented:
You will needs to see if $('#abc') returns anything in the visual studio debugger
0
 
jimbona27Author Commented:
returns [object] object

?
0
 
jimbona27Author Commented:
sorry, should be:

[object object]
0
 
jamesbaileCommented:
And can you set something in the debugger?

$('#abc').html('test')
0
 
jimbona27Author Commented:
sorry, i getting really confused now..

I need to clarify what I need.

I have a View that is a form.

on this form I need to validate 2 fields

if the fields pass validation, I need to load another view i.e. step2.

if the validation fails, i need to return a JSON object.


I need this functionality using JQUERY/ AJAX

Can I have an example of this?

thanks,
0
 
jimbona27Author Commented:
think I have this working for now..
0
All Courses

From novice to tech pro — start learning today.