In one of my View pages I have a asp.net mvc PartialView. The PartialView contains some javascript (and jquery). In my asp.net main View I load the PartialView using ajax, within a div tag, in way given below. That is, from controller I return PartialView("_DonorEdit") and in my main page I use javascript to replace the content of the div tag with the PartialView response.
<div class="content" id="content">
#{Html.RenderPartial("_DonorEdit");}
</div>
Everything works fine except the javascript contained in the partialView (_DonorEdit). Thus the question boils down to - How do I have javascript embedded in an div tag and still get it working correctly.
This problem occurs only when the partial view is returned from the ajax call. In the above code, if I directly include the PartialView (on non-ajax request), then the javascript works properly. But if I later replace the content of div using ajax request, the javascript included in PartialView does not work. The embedded javascript simply does not appear along with the Partial View. So there seems to be some other reason, why the javascript embedded in Partial View does not get passed to browser after the ajax request success.
The part of my javascript code
<script type=...>
//Date Picker. This works. I get Calendar popup as expected
$(document).ready(function () {
$("#Donor_BirthDate").datepicker({
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
yearRange: "-75:+0"
});
$("#Donor_DateLastDonated").datepicker({
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
yearRange: "-20:+1"
});
});
//Dropdown handler. Does not make it in my final View.
function residenceStateChanged(e) {
var url = '#Url.Action("_GetCities", "DropDown")';
var cmbResidenceCityId = $('#ResidenceCityId').data('tDropDownList');
cmbResidenceCityId.loader.showBusy();
$.ajax({
type: 'GET',
url: url,
data: { StateId: e.value, AddSelectOption: true, SelectOption: 'Select' },
traditional: true,
success: function (resp, textStatus, jqXHR) {
cmbResidenceCityId.dataBind(resp);
cmbResidenceCityId.select(0);
cmbResidenceCityId.trigger.change();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
},
complete: function () {
cmbResidenceCityId.loader.hideBusy();
}
});
}
....//Some other code omitted. Does not make it in final view.
</script>
I believe your problem is related to this one:
Calling a jQuery function inside html return from an AJAX call
Take a look and see if it helps.
Another way to solve the problem, is to render the partial view in the controller, an return back the html in a json object, as the ajax call result.
In the Controller, you can have a generic method to render a partial view:
private string RenderPartialView(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = this.ControllerContext.RouteData.GetRequiredString("action");
}
this.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Then, you will have to add a new action method to your controller that returns the rendered view, i.e.:
public JsonResult GetDonorEdit()
{
return Json(new
{
DonorEditContent = RenderPartialView("_DonorEdit", null)
});
}
In client side, the ajax call can be changed to something like this:
$.ajax({
type: "POST",
url: "GetDonorEdit", // get the correct url of GetDonorEdit action
cache: false
})
.success(function (result) {
$("#content").html(result.DonorEditContent);
})
.error(function (xhr, errStatus, errThrown) {
//...
});
I use this technique, because usually have to return more than one partial view in the same ajax call, and also because it properly execute the javascript code inside the partial views.
Hope it helps.
Call the javascript function in your ajax success part
If you are using this function in multiple pages, why not include it in a script file (maybe named _DonorEdit.js) and including for those pages that use the partial?
You could use something like require.js to make management of this easier.
Alternatively to require.js you can use asset bundling like Cassette.net to manage the dependencies for the pages and any partials you load via ajax.
Then, like in your binding/trigger calls inside of your ajax success handler, you can register whatever events/handlers you need to for the partial.
In the long term something you might want to look at is knockout.js: creating a viewmodel in that _DonorEdit.js file that binds against a template returned in your partial can be extremely powerful and maintainable. If you prefer to still render all the data for the partial serverside, you can still take advantage of knockout's event binding to some degree.
Related
Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.
in JavaScript
<script>
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '#Url.Action("****", "****")',true);
xmlHttpRequest.onloadend = function() {
#{
var res = (UserResponseMvc) TempData["UserResponse"];
}
#Html.ShowAlert(res?.Message)
}
xmlHttpRequest.send();
</script>
in Controller
public ActionResult Upload() {
//code
TempData["UserResponse"] = new UserResponseMvc
{
Success = true,
Message = "Upload Success"
};
return View();
}
In this piece, the code does not know the res variable.
How can I use the res variable here?
I write in Asp.net Mvc code.
Pls help me.
You can like this:
View
<input type="button" value="ClickToSend" onclick="sendToAction()" />
<script>
function sendToAction() {
var res = ["Upload1", "Upload2", "Upload3"]; // Sample
jQuery.ajax({
type: "POST",
url: "#Url.Action("Upload")", // Upload is your action in controller
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(res),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Action
[HttpPost]
public ActionResult Upload(List<String> res)
{
return View();
}
I think that can not happen
ShowAlert if only the function displays the message, then it should be a function of javascript.
You can't. and the reason is that they do not "live" in the same time.
The Razor variables are "Server side variables" and they don't exist
anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with
only HTML, CSS and Javascript code. No C# code is left, it's all get
"translated" to the client side languages.
The Javascript code DO exist when the view is still on the server, but
it's meaningless and will be executed by the browser only (Client side
again).
This is why you can use Razor variables to change the HTML and
Javascript but not vice versa. Try to look at your page source code
(CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server get a request.
The server creates "takes" the view, compute and translate all the C# code that was embedded in the view, to CSS,Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request.
the browser renders the page and executes all the Javascripts
Refer to How to pass a value to razor variable from javascript variable?
In your case, I have a some documents for you refer.
jQuery Ajax File Upload
File upload using MVC 4 with Ajax
I have a page view that makes an ajax call and updates the contents of the page with renderPartial.
So page.php -> _pagePartial.php (ajax update)
in page.php I want to include the javascript files once, then have the DOM modifications apply after the ajax rendering happens. It doesn't make sense to have this JS file load on every AJAX refresh.
For example in page.php
$baseUrl = Yii::app()->baseUrl;
$basePath = Yii::app()->basePath;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/jquery.ui.js'); // load one time!
then in pagePartial.php
// every ajax partial load
$('#sortable-list-left').sortable({
connectWith:'.productEntryCol',
placeholder: 'ui-state-highlight',
update: function(event, ui) {
var sortOrderLeft = getSortOrder('sortable-list-left');
var sortOrderRight = getSortOrder('sortable-list-right');
var projectId = '" . $project_id . "';
$.ajax({
data: { left: sortOrderLeft, right : sortOrderRight, id : projectId},
url: '/project/ajaxUpdateOrder',
type: 'POST',
success: function(response){
// process JSON response
var obj = jQuery.parseJSON(response);
}
});
}
});
The problem is after _pagePartial loads via AJAX, it can't use the .sortable() method.
What is the proper way to handle this ?
Thanks
The way I handle this is on the main view on the $.load or $.ajax or whatever it is, add your code on the success function.
So for example:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
$('#sortable-list-left').sortable({
//all your sortable code
});
});
Another option is to add your javascript on your ajax loaded page ('_pagePartial.php') into a function like so:
function firejs() {
$('#sortable-list-left').sortable({
//all your sortable code
});
}
Then on your successful ajax call on your main view ('page.php') simply add this:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
firejs();
});
You can bind to an object until it is added to the DOM and it isn't added to the DOM until the ajax call has finished successfully and the result is added to the DOM.
Also just an FYI yii has jqueryui built in you can simply say:
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Yii::app()->clientScript->registerCoreScript('jquery');
For people like me who has the same issue, even with:
Yii::app()->clientscript->scriptMap['jquery.js'] = false;
in the renderPartial and still not work. I've found another solution, way more effective I think. The easiest solution is to set the 4th parameter of renderPartial.
RenderPartial-detail
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
It is about processOutput.If you put it to true, then Jquery will be loaded in your render Partial.
Hope this will help someone...
I am working a site in ASP.NET MVC where the user is presented with a calendar, and clicking on a particular calendar date invokes the following function:
function selectHandler(event, data) {
var myRequest = new Request.HTML({
url: '/Calendar/EventList',
method: 'post',
data: { datedata: data.toString() },
update: $('postback'),
}).send();
};
I am using the MooTools AJAX classes to invoke my Controller Action /Calendar/EventList, shown below:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EventList(string datedata)
{
CalendarViewData viewData = new CalendarViewData
{ EventList = GetEventsList(datedata) };
return View(viewData);
}
I can set a breakpoint in the EventList action, and see that it is returning the view, but the browser remains on the initial page, and never redirects to the page returned by this EventList action.
I suspect I need to add more to my JavaScript function but am not sure what. Any ideas?
Why would the browser redirect? You are sending an AJAX request to a controller action which returns a view (this probably is wrong, you might need to return a partial view) which is then used to update some element in the DOM. If you want to redirect you could use a simple anchor tag (or a form if you need to POST), no need to use javascript.
Can I call javascript function from MVC controller action (not from view page) and get return value? How?
I need to make request to server from code (.cs) using javascript like here (but this is aspx page)
function getInitData() {
var code; code = 'return {' ;
code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
code += '};'
VK.Api.call('execute', { 'code': code }, onGetInitData);
}
For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.
First, create a string property on your Model.
public class MyModel
{
public string JavascriptToRun { get; set;}
}
Now, bind to your new model property in the Javascript of your view:
<script type="text/javascript">
#Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
<script type="text/javascript">
#Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
Finally, in your controller action, you need to call this new Javascript function:
[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
// Do something useful
...
if (success == false)
{
model.JavascriptToRun= "ShowErrorPopup()";
return View(model);
}
else
return RedirectToAction("Success");
}
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.
An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
error : function(req, status, error) {
// do something with error
}
});
Yes, it is definitely possible using Javascript Result:
return JavaScript("Callback()");
Javascript should be referenced by your view:
function Callback(){
// do something where you can call an action method in controller to pass some data via AJAX() request
}
It is late answer but can be useful for others.
In view use ViewBag as following:
#Html.Raw("<script>" + ViewBag.DynamicScripts + "</script>")
Then from controller set this ViewBag as follows:
ViewBag.DynamicScripts = "javascriptFun()";
This will execute JavaScript function.
But this function would not execute if it is ajax call.
To call JavaScript function from ajax call back, return two values from controller and write success function in ajax callback as following:
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
success: function(result, para) {
if(para == 'something'){
//run JavaScript function
}
},
error : function(req, status, error) {
// do something with error
}
});
from controller you can return two values as following:
return Json(new { json = jr.Data, value2 = "value2" });
There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.
We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.
In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.
If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt)
So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:
void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
if(search != null)
{
search.SetAttribute("value", "Superman");
foreach(HtmlElement ele in search.Parent.Children)
{
if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
{
ele.InvokeMember("click");
break;
}
}
}
}
So probably nowadays, that would not be the easiest solution.
The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.
Some related questions on this topic or possible duplicates:
Embedding JavaScript engine into .NET
Load a DOM and Execute javascript, server side, with .Net
Hope this helps.
The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
<script>
$(document).ready(function () {
var msg = '#ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>