I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});
Related
I have to perform following operation.
On a button click from View1, do Ajax request and get complex object as return.
Pass this object to View2 as parameter.
Process the data sent from view1 in client side(inside $(window).load()).
Below is my code:
View1 :
var Url = baseUrl() + "/InteractiveReport/GetRatingProfitData/";
$.ajax({
type: "POST",
url: Url,
contentType: "application/json; charset=utf-8",
dataType: "html",
// dataType: "json",
data: JSON.stringify({ "Projects": SelectedProjectinfo }),
success: function (JsonData) {
debugger;
var w = window.open('about:blank');
w.document.open();
w.document.write(JsonData);
w.document.close();
},
error: function (retVal) {
alert("error:" + retVal.responseText);
}
});
InteractiveReportController :
public ActionResult RatingProfitReport(ProfitRatingInfoModel RatingProfitData)
{
return View("RatingProfitReport", RatingProfitData);
}
public ActionResult GetRatingProfitData(IRSelectedProjectInfoModel Projects)
{
ProfitRatingInfoModel RatingProfitData = new ProfitRatingInfoModel();
//GET RatingProfitData from Database
return RatingProfitReport(RatingProfitDataMdl);
//var jsonSerializer = new JavaScriptSerializer();
//string response = jsonSerializer.Serialize(RatingProfitDataMdl);
//return Json(response, JsonRequestBehavior.AllowGet);
}
View2 :
#using Enterprise_Dashboard.Models
#model ProfitRatingInfoModel
<script>
//Control not entering this section
$(document).ready(function () {
init_bind_rating_profit_table();
});
function init_bind_rating_profit_table()
{
debugger;
var RatingProfitData = #Model.ProfitRatingData;
alert(RatingProfitData[0].BU);
}
</script>
Is there any better way to redirect to different view from Ajax call with parameters.
from my View1, if i directly make Ajax call to View2, i cannot pass complex object as parameter, since its too big string.
Is there any way i can set RatingProfitDataMdl into Session or ViewBag or ViewData or anything else and i can access it in View2?
OR
Is there any way i can eliminate Ajax call on button click so button click on View1 will automatically call GetRatingProfitData and it internally redirects to RatingProfitReport with modal object parameter?
OR
Completely different approach available to handle this scenario?
I am developing MVC 5 App. I have a Parent View that call a Partial View, where user can Load a Image.
On Submit a call a .Ajax defined in Parent view that call Method/Controller.
What I need is to send to the controller data I have in Parent View. Is that Posible?
Here is my code.
Parent View
Partial View
.Ajax Method
$('#formPhoto').submit(function (event) {
event.preventDefault();
if ($(this).valid()) {
var id="aaa";
var formdata = new FormData($(this).get(0));
$.ajax({
url: this.action,
type: this.method,
data:formdata,
processData: false,
contentType: false,
beforeSend: function () {
return true;
},
success: function (result) {
successPhoto();
},
complete: function () {
// alert(3);
// And so on.
}
});
}
return false;
});
I need to send var aa='aaa' in data:
Yes it's possible. So basically I can suggest for you two ways to do what you need:
1st: You could consider putting the form element in the ParentView and change your code a little bit...
2nd: You could recover the data from the parent view and serialize it together to send to your action.
So, from the second option it would be something like:
var parentInformation = 'aaa';
var formdata = new FormData($(this).get(0));
formdata.ExpectedParentOnPropertySide = parentInformation;
Please, I hope this solve your problem
I have a link when pressed it requests a page from a controller via render ajax, Previously i used to pass only the id but now i would like to pass an extra parameter to the controller, how do i achieve this,
This is what i have tried
This is the link' which only passes a single parameter to the controller
Html::a('click me', ['#'],
['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed
'id' => 'perform']);
This is the controller code expecting 2 parameters:
public function actionChecktruck($id,$category) //it expects 2 parameters from above link
{
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
This is my jquery code of another button that depends on the above controller during post request
$("#postbutn").click(function(e) {
$.post("checktruck?id="+truckid, //here i would like to pass 2 params
{checked:checked,unchecked:unchecked,truckid:truckid}
)
}
This is the jquery code when there is no post
How can i pass an extra parameter in the link or even the $.post request for the controller
First of all, as you are using JQuery ajax to submit the form, there is no need to set value for the link
Html::a('click me', ['#'],['id' => 'perform']);
using this id you can submit the request as follows
$this->registerJs("$('#perform').click(function(event){
event.preventDefault(); // to avoid default click event of anchor tag
$.ajax({
url: '".yii\helpers\Url::to(["your url here","id"=>$id,"param2"=>param2])."',
success: function (data) {
// you response here
},
});
});");
There is no need to mention method attribute as 'POST', you want to send through GET method
And finally in your controller, you need to accept parameters as follows
public function actionChecktruck() //it expects 2 parameters from above link
{
$id = Yii::$app->request->queryParams['id'];
$param2 = Yii::$app->request->queryParams['param2'];
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
Try this one,
In View file
$this->registerJs("$('#postbutn').click(function(){
$.ajax({
url: '".yii\helpers\Url::to(["u r URL"])."',
method: 'POST',
data: {id:id, truckid:truckid },
success: function (data) {
},
});
});");
What I'm trying to achieve is to update some part of a page containing partial views. My attempt on doing so is below:
$.ajax({
type: 'GET',
url: actionUrl,
success: function (data) {
$("#results").html("");
$("#results").append(#Html.Partial("_FirstPartial", data.FirstDataSet));
$("#results").append(#Html.Partial("_SecondPartial", data.SecondDataSet));
}
});
Of course I couldn't pass JS variables to ASP MVC methods like that, so how could I? Or probably there is a completely different, better approach for the way I could update the page?
View (Javascript):
$.ajax({
type: 'GET',
url: actionUrl,
success: function (data) {
$("#results").html("");
$.post('#Url.Action ("FirstPartial")',{data:data.FirstDataSet},function(ret){
$("#results").append(ret);
$.post('#Url.Action ("SecondPartial")',{data:data.SecondDataSet},function(ret2){
$("#results").append(ret2);
}
}
}
});
Controller:
public ActionResult FirstPartial(string data)
{
return PartialView("_FirstPartial", data);
}
public ActionResult SecondPartial(string data)
{
return PartialView("_SecondPartial", data);
}
You need to use Partial Actions (that returns a partial view). In javascript, after getting datasets you call another partial action to render datasets.
I nested two ajax calls to render the second view below the first view. If you remove the nesting then the second one may render before the first one.
Make in your controller method which returns partial you want, then in your Index.cshtml file make something like this:
<script>
var Services = {
linkToPartial: '#Url.Action('MethodName', 'Controller')'
}
</script>
This code will provide an action link which you can use in your $ajax success method and provide arguments.
$("#results").html("");
$.ajax({
method: 'GET',
url: Services.linkToPartial,
data: {
argumentName: data.FirstDataSet
}
}).done(function (html) {
$('#results').append(html);
});
I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;