-1

I want to make previews of one view on a homepage type view. To do so, I'd like to call a ListPreviews Action. I want this action to get the html body of a given view and then take the first hundred characters or so.

How can I access the actual html of a view from a controller?

1
  • Can you please let me know how I can help you further?
    – kblau
    Commented Jun 12, 2017 at 21:32

1 Answer 1

0

This should be simple. In your RouteConfig.cs set the defaults, mine looks like this:

defaults: new { controller = "Home", action = "Index2006", id = UrlParameter.Optional }

For your Controller/Model:

public class AView
{
    public string theHtml { get; set; }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index2005(AView AView)
    {
        //put breakpoint here to see all the <html> here in view
        var result = HttpUtility.UrlDecode(AView.theHtml, System.Text.Encoding.Default);
        return Json(new
        {
            Greeting = "Returning data not used"
        }
        , @"application/json");
    }

For your view:

<!DOCTYPE html>
<html id="PassMe">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2005</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".btn").click(function () {
                var AView = { theHtml: escape($("#PassMe").html()) };  //JSON.stringify($("#PassMe").html())
                $.ajax({
                    url: '/Home/Index2005',
                    type: 'POST',
                    data: AView,
                    success: function (result) {
                        $("#detail").append(result.Greeting);
                    },
                    error: function (result) {
                        alert('Error');
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button style="margin-bottom: 20px;" class="btn  btn-default">Click to pass HTML</button>
</body>
</html>
1
  • @bchattdeveloper Can you please let me know how I can help you further?
    – kblau
    Commented Jun 12, 2017 at 19:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.