Rectangle 27 3

I remember having a similar problem before. We added a dialog container and then loaded the partial view in an inner div.

<div id="dialogcontainer">
    <div id="dialogcontent"></div>
</div>

$("#dialogcontainer").dialog({
    width: 400,
    resizable: false,
    title: 'Test dialog',
    open: function(event, ui) {
        $("#dialogcontent").load("@Url.Action('TestAction')");
    },
    buttons: {
        "Close": function (){
            $(this).dialog("close");
        }
    }                        
});

asp.net mvc - MVC 2 - Display a jquery dialog that contains a partial ...

asp.net-mvc asp.net-mvc-2
Rectangle 27 8

Rather than bind the events to your buttons directly, anchor them to a containing block that doesn't get refreshed. your events will continue to fire even if you have reloaded the inner content in that partial view.

$("#container").on("click",".btn.mylink", function (evt) {            
        var id = $(evt.currentTarget).data('id');
        var url = "/SalidaDetalle/Edit/" + id;            
        $.get(url, function (data) {
            $(".modal-body").html(data);
            $('#myModal').modal('show');
        });
    });

$("#container").on('submit',".edit-detail", function (evt) {
         $.post($(evt.currentTarget).attr('action'),
         $(evt.currentTarget).serialize(), 
         function (data, status) {                        
             $('#myModal').modal('hide');
               $("#details").html(data);

         }).error(function (error, status, a, b) {
              writeError('msgError', 'Error processing request. Please check errors and try again!');
            $('.modal-body p.body').html(error.responseText);

   });
   return false;
   });

You'll need to tweak the script and add the div with id container to your parent view, but you get the idea

Ok so, should I go with delegate event over binding event on ajax call? I read in other question that it is not recommended and that is why i do it like this.

this is not working on chrome

ajax - jQuery events stop working after partial view post in asp.net m...

jquery ajax asp.net-mvc twitter-bootstrap asp.net-mvc-4
Rectangle 27 4

Building on @Darin-Dimitrov pattern answered above, I passed a model into a partial view, which I loaded into a _Layout page.

I needed to load a web page from an external resource on Application Load, which will be used as the header navigation across multiple sites. This is in my Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    Application["HeaderNav"] = GetHtmlPage("https://site.com/HeaderNav.html");
}

static string GetHtmlPage(string strURL)
{
    string strResult;
    var objRequest = HttpWebRequest.Create(strURL);
    var objResponse = objRequest.GetResponse();
    using (var sr = new StreamReader(objResponse.GetResponseStream()))
    {
        strResult = sr.ReadToEnd();
        sr.Close();
    }
    return strResult;
}
public class ProfileController : BaseController
{
    public ActionResult HeaderNav()
    {
        var model = new Models.HeaderModel
        {
            NavigationHtml = HttpContext.Application["HeaderNav"] as string
        };
        return PartialView("_Header", model);
    }
}

I loaded the partial view in the _Layout page like this.

<div id="header">
     @{Html.RenderAction("HeaderNav", "Profile");}
</div>

The partial view _Header.cshtml is very simple and just loads the html from the application variable.

@model Models.HeaderModel
@MvcHtmlString.Create(Model.NavigationHtml)

c# - How do you access application variables in asp.net mvc 3 razor vi...

c# asp.net-mvc-3 razor
Rectangle 27 6

As Partial View is loaded via ajax you need to initialize datepicker after the html is rendered on page so you need to put datepicker initialization script in success function callback:

$.post($(this).attr('action'), $(this).serialize(), function (data, status) {
                    $('#myModal').modal('hide');
                    $("#details").html(data);
                    $("#textBoxID").datepicker(); //  initialize datepicker for partial view element here

                })

For events you can write delegated events to make them work,choose the closest element of the partial view, i am using container of partial in which you are appending partial view html:

$("#details").on("click","#someButtonId",function(){

// write event code here

})

Ehsan, that worked!, This is a step forward, please what about the events, there is something else i have to do?

@Elio.Batista: anything and everything that needs to be initialized on something in the partial view (event handlers, etc.) must go in the call back. Otherwise, the actual elements you're trying to bind to don't exist yet.

Events can be written in main view but you have to write delegated event

True, but you have to be careful with delegated events. They should be used sparingly and the element you bind to should be as close as possible in the DOM to the element generating the event: e.g., #myModel is good, document would be very bad.

c# - Using jQuery with partial views in asp.net mvc 4 - Stack Overflow

c# jquery ajax asp.net-mvc twitter-bootstrap
Rectangle 27 3

Since a partial view is loaded after the main page, the button click event isn't tied to the button. To get it to work you need to attach your click event to the document. Give your button a class to select on:

<input type="button" value="Confirm interview" class="btnConfirm"/>
$(document).on('click', '.btnConfirm', function(){
    $.ajax({
        url: '@Url.Action("Action", "Controller")',
        type: 'POST',
        cache: false,
        async: true,
        data: $('form').serialize(),
        success: function(result){
            //do something
        }
     });
});

When I click the button I want to submit my model. I want to avoid posting my model as a JSON string using jQuery. I don't know my click event code would be inside the jQuery?

what are you wanting to do? My code would allow you to do an ajax call and save just the partial view data but that would be using JSON. Is there a reason you don't want to use JSON?

In the past I've had my model as a parameter and it's more straightforward because I already have the object. I am having problem passing my model to the javascript. Do you have any good code for this?

if you put a form tag around your partial view you can do a form.serialize to pass the fields from the partial. see my changed code above

I am no longer in the office but I will definitely give this ago tomorow and reply back.

asp.net mvc 4 - MVC 4 button not working in partial view - confusion o...

asp.net-mvc-4 post view partial-views
Rectangle 27 7

but partial view has reloaded I can no longer perform a new Search by clicking the ENTER key

You should use event delegation .on() since the element with id Search will be added dynamically after the reload, simple keyup event can't deal with fresh DOM :

$("body").on("keyup", "#Search", function(event){
    if(event.keyCode==13){
        alert("Index.cshtml - Enter Pressed - Method inside Document.Reader().");
        searchAssets();
    }
});

This actually does the job @AnalyticLunatic wants.. this happens because $("#Search").keyup(function(event) is ran when document is ready and at that point, the change it makes wont no longer be the same object and jQuery will not know where to look because the code is not being executed again... I say this just to explain why this happens and why the shown code works

asp.net mvc - jQuery keyup event not working after partial view reload...

jquery asp.net-mvc asp.net-mvc-5 asp.net-mvc-partialview
Rectangle 27 7

Sections don't work the same way in partial views. In order to achieve what you're after, your going to have to move your scripts to a file, include an HTML helper, then call that HTML helper to render your scripts for each partial view that is loaded.

asp.net mvc - Razor MVC render section - Stack Overflow

asp.net-mvc asp.net-mvc-4 razor partial-views
Rectangle 27 7

Sections don't work the same way in partial views. In order to achieve what you're after, your going to have to move your scripts to a file, include an HTML helper, then call that HTML helper to render your scripts for each partial view that is loaded.

asp.net mvc - Razor MVC render section - Stack Overflow

asp.net-mvc asp.net-mvc-4 razor partial-views
Rectangle 27 2

$(document).ready won't work in a partial. It is only executed when the page is loaded initially.

So you need to shift those scripts, inside the partial, to the callback function of your ajax call.

Thanks for the response. That's what I gathered, but nothing I tried had worked. The answer turned out to be a combination of that AND this: stackoverflow.com/questions/12978254/ For reasons I don't really understand I had to add .datepicker{z-index:1151;} to my css.

Hmm strange. The z-index fix looks like the datepicker was hiding behind the modal. Bootstrap modal has a z-index of 1050 hence datepicker is given a higher z-index value.

asp.net mvc 4 - Getting jquery event to fire for element in ajax loade...

jquery asp.net-mvc-4 twitter-bootstrap asp.net-ajax
Rectangle 27 4

Once your view is rendered the only way to load a partial view is via an Ajax call which returns the partial view to your JQuery/Javascript and then updates the DOM accordingly.

<a href="#" id="loadViewButton">Load view</a>
<div id="partialViewContainer"><!-- your partial view will be loaded in here --></div>
$('#loadViewButton').on('click', function() {
    $.ajax({
        type: "GET"
        url: '/YourController/YourAction',
        success: function (data, textStatus, jqXHR) {
            $('#partialViewContainer').html(data);
        }
    });
});
[HttpGet]
public ActionResult YourAction()
{
  return View("YourView");
}

asp.net mvc - How to load partial view on clicking Html.ActionLink? - ...

asp.net-mvc asp.net-mvc-5 asp.net-mvc-partialview
Rectangle 27 1

since a partial view isn't loaded when the page loads the scripts on the main page won't trigger for the partial unless you put the functions in a main function that is called after the partial load or you tie the click events to the document

$(document).on('click', '.btnSubmit', function(){
    //your code here
});

if you have a button on your partial with class="btnSubmit" this code will trigger on the main page when it is clicked

asp.net mvc - Scripts not rendering in partial view - Stack Overflow

asp.net-mvc asp.net-mvc-4
Rectangle 27 10

@Marius Schulz gives a nice reference, but then misses the point. Yes, the underscore helps to differentiate between full views and partial ones, but more importantly, it prevents partial views from being loaded directly by their URL, which could provide some potentially ugly results! (Like no css, for starters.)

EDIT: Mystere Man is right...what was I thinking? URLs in MVC point to controller/action, not to view.

Also, it is possible to mess things up and display a partial in a seperate window, so the naming convention does not prevent that. @Marius Schulz and I had the same misinterpretation of his quote.

The leading underscore is a useful convention to differentiate full and partial views, and I will continue to use it, but is is just a convention, not a functional difference.

This is the correct answer, it is more than just an MVC convention.

@Marius, sorry for the nitpicking, I guess I felt like your follow up after the block quote de-emphasized that bit, and made it sound more like the "just a convention" answer.

@EdDeGagne - no, it's not the correct answer. MVC prevents ALL views from being loaded directly, underscore or not. The underscore was originally used in ASP.NET Web Pages, where views could be load directly, but this doesn't apply to MVC.

Why do I need an underscore for partial views in asp.net mvc - Stack O...

asp.net-mvc partial-views
Rectangle 27 4

I also had a similar issue. Hope this helps. We wanted to have a view that contains a common header section that displays some data and another section that should dynamically change when we click on a link in our page. (something similar to a tab) Since we didn't want to reload the header section multiple times, we decided to have a container view and a place holder div that will be used to load a partial view dynamically when we click on a ajax link. However, partial views that got loaded into the place holder had lot of javascript code and we couldn't include all the code that were used by different partial views into a single javascript file and refer it from the container view as there were some conflicting functions. Introducing namespaces to fix that issue also wasn't very efficient approach as all the javascript logic would still have been loaded unnecessarily. Doing a bit of googling made me realize that having a script section in a partial view is not going to work. I tried to define a section in my view using @RenderSection("partialScripts", required: false) unsuccessfully as RenderSection only works in a layout view. Following is the approach i took to overcome this issue. scripts section that is defined in the layout view can contain any valid markup. so i decided to have a div that will help me to load scripts dynamically inside the scripts section of my container view. OnSuccess event handler of the action link was used to attach the scripts dynamically. Here is the code for my container view.

<ul>
    <li>
        @Ajax.ActionLink("Partial One", "PartialOne", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialOne')"
                     })
    </li>
    <li>
        @Ajax.ActionLink("Partial Two", "PartialTwo", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialTwo')"
                     })
    </li>
</ul>

<div id="container">
</div>

@section scripts
{
    <script src="@Url.Content("~/Scripts/app/Container.js")"></script>
    <div id="dynamicScripts"
         data-partial-one="@Url.Content("~/Scripts/App/PartialOne.js")"
         data-partial-two="@Url.Content("~/Scripts/App/PartialTwo.js")">
    </div>
}

Code from the controller class

public PartialViewResult PartialOne()
    {
        return PartialView("_PartialOne");
    }

    public PartialViewResult PartialTwo()
    {
        return PartialView("_PartialTwo");
    }

Container.js file contains the logic that will dynamically load the necessary scripts for different partial views.

function loadScriptsDynamically(name) {
    var script = document.createElement('script');
    var dynamicScriptsDiv = document.getElementById('dynamicScripts');
    var dynamicScriptDivJQuery = $('#dynamicScripts');
    dynamicScriptDivJQuery.empty();
    if (name === 'PartialOne') {
        script.src = dynamicScriptDivJQuery.data('partial-one');
        dynamicScriptsDiv.appendChild(script);
    } else if (name === 'PartialTwo'){
        script.src = dynamicScriptDivJQuery.data('partial-two');
        dynamicScriptsDiv.appendChild(script);
    }
}

We can't use jQuery to append a script element to a div due to some restrictions. But we can use some old fashioned javascript code to create a script element and append it to dynamicScriptsDiv. Please note that i am accessing the script paths i previously attached to dynamicScriptsDivusing using some data- attributes as our MVC app runs in IIS server and we didnt want to hard code them.

Attaching to events after the script is dynamically loaded was our next challenge. By using an immediate invocation function i was able to register all my event binding code and any initialization logic i have to perform using following code.

(function initPartialOne() {
    $('#myButton').click(function() {
        setLabelText();
    });
})();

function setLabelText() {
    $('#myLabel').text('One was clicked');
}
<label id="myLabel">[Message]</label>
<input type="button" id="myButton" value="Click me partial one"/>

asp.net - Use Sections in Partial Views in MVC 4.0 - Stack Overflow

asp.net .net asp.net-mvc razor asp.net-mvc-4
Rectangle 27 4

I also had a similar issue. Hope this helps. We wanted to have a view that contains a common header section that displays some data and another section that should dynamically change when we click on a link in our page. (something similar to a tab) Since we didn't want to reload the header section multiple times, we decided to have a container view and a place holder div that will be used to load a partial view dynamically when we click on a ajax link. However, partial views that got loaded into the place holder had lot of javascript code and we couldn't include all the code that were used by different partial views into a single javascript file and refer it from the container view as there were some conflicting functions. Introducing namespaces to fix that issue also wasn't very efficient approach as all the javascript logic would still have been loaded unnecessarily. Doing a bit of googling made me realize that having a script section in a partial view is not going to work. I tried to define a section in my view using @RenderSection("partialScripts", required: false) unsuccessfully as RenderSection only works in a layout view. Following is the approach i took to overcome this issue. scripts section that is defined in the layout view can contain any valid markup. so i decided to have a div that will help me to load scripts dynamically inside the scripts section of my container view. OnSuccess event handler of the action link was used to attach the scripts dynamically. Here is the code for my container view.

<ul>
    <li>
        @Ajax.ActionLink("Partial One", "PartialOne", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialOne')"
                     })
    </li>
    <li>
        @Ajax.ActionLink("Partial Two", "PartialTwo", ajaxOptions: new AjaxOptions
                     {
                         HttpMethod = "Get",
                         InsertionMode = InsertionMode.Replace,
                         UpdateTargetId = "container",
                         OnSuccess = "loadScriptsDynamically('PartialTwo')"
                     })
    </li>
</ul>

<div id="container">
</div>

@section scripts
{
    <script src="@Url.Content("~/Scripts/app/Container.js")"></script>
    <div id="dynamicScripts"
         data-partial-one="@Url.Content("~/Scripts/App/PartialOne.js")"
         data-partial-two="@Url.Content("~/Scripts/App/PartialTwo.js")">
    </div>
}

Code from the controller class

public PartialViewResult PartialOne()
    {
        return PartialView("_PartialOne");
    }

    public PartialViewResult PartialTwo()
    {
        return PartialView("_PartialTwo");
    }

Container.js file contains the logic that will dynamically load the necessary scripts for different partial views.

function loadScriptsDynamically(name) {
    var script = document.createElement('script');
    var dynamicScriptsDiv = document.getElementById('dynamicScripts');
    var dynamicScriptDivJQuery = $('#dynamicScripts');
    dynamicScriptDivJQuery.empty();
    if (name === 'PartialOne') {
        script.src = dynamicScriptDivJQuery.data('partial-one');
        dynamicScriptsDiv.appendChild(script);
    } else if (name === 'PartialTwo'){
        script.src = dynamicScriptDivJQuery.data('partial-two');
        dynamicScriptsDiv.appendChild(script);
    }
}

We can't use jQuery to append a script element to a div due to some restrictions. But we can use some old fashioned javascript code to create a script element and append it to dynamicScriptsDiv. Please note that i am accessing the script paths i previously attached to dynamicScriptsDivusing using some data- attributes as our MVC app runs in IIS server and we didnt want to hard code them.

Attaching to events after the script is dynamically loaded was our next challenge. By using an immediate invocation function i was able to register all my event binding code and any initialization logic i have to perform using following code.

(function initPartialOne() {
    $('#myButton').click(function() {
        setLabelText();
    });
})();

function setLabelText() {
    $('#myLabel').text('One was clicked');
}
<label id="myLabel">[Message]</label>
<input type="button" id="myButton" value="Click me partial one"/>

asp.net - Use Sections in Partial Views in MVC 4.0 - Stack Overflow

asp.net .net asp.net-mvc razor asp.net-mvc-4
Rectangle 27 4

your scripts are in a document.ready but since your partial view is loaded after that the scripts don't affect your partial. How I solve this is to put the script that I want to run on a partial in a function

function AttachScript(){
    //your script here
}

and then call that function after you have loaded the partial view

$('#placeholder-districts-summary').html(data);
AttachScript();

I have since learned that you can attach the click event to the document and attach your script that way

$(document).on('click', '.clsButton', function(){
     //do something
 });

with this the script it attached to the document and this will fire even if it is on a partial that is loaded after the page load.

Thanks a million, Matt. This works perfectly!

asp.net mvc 4 - How can jQuery DataTables be applied to AJAX rendered ...

jquery asp.net-mvc-4 datatables
Rectangle 27 7

ko.applyBindings(someViewModel, someDomElement)

However, if you have an overall view model bound to the page and then "islands" of content that are loaded via a partial that you want to bind later, then one option would be to go for something like this: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html. So, you would set up a binding on the container of where your partial goes that tells Knockout to keep its hands off of that area. Then when you load the partial, you can safely call ko.applyBindings(someViewModel, innerContainer).

ko.bindingHandlers.stopBinding = {
    init: function() {
        return { controlsDescendantBindings: true };
    }
};

and you would use it like:

<div id="outerContainer" data-bind="stopBinding: true">
    <div id="innerContainer">
     ...load your partial here
    </div>
</div>
ko.applyBindings(someViewModel, document.getElementById("innerContainer"));

asp.net mvc 4 - How do I rebind the knockout viewmodel when the page i...

ajax asp.net-mvc-4 knockout.js
Rectangle 27 7

ko.applyBindings(someViewModel, someDomElement)

However, if you have an overall view model bound to the page and then "islands" of content that are loaded via a partial that you want to bind later, then one option would be to go for something like this: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html. So, you would set up a binding on the container of where your partial goes that tells Knockout to keep its hands off of that area. Then when you load the partial, you can safely call ko.applyBindings(someViewModel, innerContainer).

ko.bindingHandlers.stopBinding = {
    init: function() {
        return { controlsDescendantBindings: true };
    }
};

and you would use it like:

<div id="outerContainer" data-bind="stopBinding: true">
    <div id="innerContainer">
     ...load your partial here
    </div>
</div>
ko.applyBindings(someViewModel, document.getElementById("innerContainer"));

asp.net mvc 4 - How do I rebind the knockout viewmodel when the page i...

ajax asp.net-mvc-4 knockout.js
Rectangle 27 2

If you are including a Partial view called Foo.cshtml you could also create a partial view named FooScripts.cshtml and render that view where the rest of your scripts are getting loaded:

<h2>Main View</h2>

@Html.Partial("Foo")

...


@section scripts {
    @Scripts.Render("~/bundles/jquery")
    @Html.Partial("FooScripts")
}

Sorry that after asking the question I had to go and again after leaving this comment there would be a delay before my next comeback. I knew the subject you mentioned but didn't think of it as the solution. And maybe it could be in the correct path to the solution. So this way you mean I should place "$('#myModal').show();" in the jquery's Ready function where all the plugins are initialized. Right? Also the part the Jquery is looking for to run is a conditional part which would be hidden in the usual time: "id="myModal"". (Continued...)

after a submit happend during a "post" method and again it returned back to the view I want that JQuery's plugin take place and show the "myModal". If you could please address the issue I mentioned, if you are sure that this will work without any change let me know. A more clarified version is more appreciated. Thanks for the info +1

asp.net mvc - Call Jquery function inside razor's subviews - Stack Ove...

jquery asp.net-mvc razor
Rectangle 27 1

There are many things you're not doing quite right. First, jQuery should be loaded in your layout file (in the head section), not in your partial view (I assume Create.cshtml is partial). jQuery needs to be loaded as early as possible (and should be the first script you load), and it should be loaded before the page is rendered. By putting it so far in, you are just asking for trouble.

I would also load the jquery.validation and jquery.validation.unobtrusive in the layout as well.

If you can do so, i'd download the MVC4 beta, and generate a default internet application. The MVC4 default app uses a popup login dialog, that includes validation and does not go away if the validation fails.. exactly what you're looking for. You should be able to adapt their code to your own needs.

Also, make sure you have the latest versions of jQuery.validation, and jQuery.validation.unobtrusive. Use NuGet to retrieve the latest versions of everything.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - MVC 3 How to make a form with Post Redirect Get method while main...

c# asp.net-mvc-3 post-redirect-get
Rectangle 27 1

You cannot pass back the partial view as that returns the partial view only - not the view + the loaded partial view inside the modal. So what your seeing currently is correct.

You'll need to pass back a JSON response using AJAX in order for it to validate within the modal's partial view.

If the model state isn't valid, return the key-value pairs of the model-state. A good starting example is here: Example

Once that is sent back to your view, you can use jquery to append the model errors (if any) onto the validation summary area.

Example as requested -

public class HomeController : BaseController
{
    [HttpPost]
    public ActionResult Edit(EditViewModel vm)
    {
        if(ModelState.IsValid)
        {
             //do stuff
             return Json(new
             {
                 status = "success"
                 //return values if needed
             }
        }
        return Json(new
        {
            status = "failure",
            formErrors = ModelState.Select(kvp => new { key = kvp.Key, errors = kvp.Value.Errors.Select(e => e.ErrorMessage)})});
        }
    }
}
@using (Ajax.BeginForm("Edit", new AjaxOptions { OnSuccess = "onChangeSuccess"}))
{
    //Modal header, body, footer
    //Make sure your form fields actually contain their Razor validation fields
}
function onChangeSuccess(data) {

    if (data.status === "success") {
        $("#modalcontent").modal('hide');
        $("#message-area").html(data.view);
    }
    $.each(data.formErrors, function() {
        $("[data-valmsg-for=" + this.key + "]").html(this.errors.join());
    });
}

Thanks....by chance do you know of an example of this implemented in a modal?

jquery - MVC 5 with Bootstrap Modal from partial view validation not w...

jquery asp.net-mvc twitter-bootstrap asp.net-mvc-5