views:

60

answers:

3

I have my views render to route requests like /controller/action (for instance, /Page/Create), so pretty classic.

I am creating a form where view will be loaded through AJAX request with jQuery get(), so essentially I need my Views or to be precise, my controller actions, to return plain HTML string when an AJAX request is made to the route that renders the View. I want to use the same views as for normal requests, so I cannot afford to create any new views.

It is something like calling RenderPartial("MyViewUserControl") but from inside the JS code.

A: 

You need to move the HTML strings to partial views, then include the partial views in your regular views (if applicable) and render the partial views in your actions.

You'll probably want to use the Request.IsAjaxRequest() extension method in the actions.

To get the HTML in Javascript, you can make a normal AJAX request to the action's URL.

SLaks
A: 

There's nothing special you need to do here - just request your action methods with .get() like normal, and set your response type to "html".

$.get('<% Url.Action("MyActionMethod") %>', { },
   function(data){
     alert("Data Loaded: " + data);
   },
   "html")
womp
This is true if my views include all the form code but in fact I have my form in ASCX. Something like SLaks says..
mare
A: 

My answer based on SLAks response - I'm archiving this for later reference or to help someone else.

This is my structure:

1) Create.aspx (ViewPage) uses RenderPartial("Tab-CreateEditForm") to render the create/edit form, which is 2) Tab-CreateEditForm.ascx (the partial) 3) Create action that detects what kind of request is being made. If we are making AJAX request we probably don't want to render Create.aspx which is by default and instead rather render Tab-CreateEditForm because it contains only the form tag and fields and NO page directives, head, title and all the other elements that are in Create.aspx.

So the action looks like this:

    //
    // GET: /Tab/Create/{tabGroupSlug}
    [CanReturnModalView]
    [Authorize(Roles = "Administrators")]
    public ActionResult Create(string tabGroupSlug)
    {
        Tab tab = new Tab();
        if (Request.IsAjaxRequest())
            return View("Tab-CreateEditForm", tab); // returns partial

        return View(tab); // returns Create.aspx 
    }

And this is my Edit action which also uses the same technique because the Edit View (Edit.aspx page) also uses the same editing partial control.

    //
    // GET: /Tab/Edit/{slug}
    [CanReturnModalView]
    [Authorize(Roles = "Administrators")]
    public ActionResult Edit(string slug)
    {
        Tab editing = (Tab) _repository.GetInstance(slug);
        if (Request.IsAjaxRequest())
            return View("Tab-CreateEditForm", editing); // returns partial

        return View(editing); // returns Edit.aspx
    }
mare