Pass the result of AJAX callback to Partial View using JQuery - javascript

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method and return the data needed as Json Data. I'm able to do this using the following code:
<script>
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
datatype: "json",
success: function (data) {
debugger
}
});
});
});
[HttpPost]
public JsonResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return Json(items);
}
In success function, the collection of Items are returned properly. In this function, I want to call Html.Partial and pass the result as the model of the Partial view. Is this possible?
I've searched in other threads, but most of them are suggesting that Partial View is returned from Controller method and html(data) is used to render it. I'd rather not return the Partial view from Controller, as the size would have significant difference rather than returning the data only and render it manually in client-side.
So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?
Any help is appreciated. Thanks!

so what's the problem? just do it
[HttpPost]
public ActionResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return View("MypartialView",items);
}
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
success: function (data) {
$("#div").html(data);
}
});
});
});

So, is it possible to pass the result to Partial view in success
function, or I have to manually render the elements in there?
you can solve this problem in couple of way -
use AJAXFORM Post.
Alternatively you can use JQuery templates.
JQuery Templates solution
First reference following JQuery libraries -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>
Then create the template which you want to fill up with details -
<script id="personsTmpl" type="text/x-jquery-tmpl">
<tr>
<th>${Name}</th>
</tr>
</script>
As a next step define the Table in html -
<table id="tableAttendees">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tr></tr>
</table>
Have a button on the page -
<input type="button" value="Click" onclick="submitForm()" />
Finally handle the JQuery Click event of the Submit button -
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("Submit")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: "Rami" }),
success: function (data) {
$("#personsTmpl").tmpl(data).appendTo("#tableAttendees");
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
When the button is clicked, Submit Action will be hit -
public ActionResult Submit(string name)
{
return Json(new Person() { Name = name + " Its Me" });
}
which would return person object -
public class Person
{
public string Name { get; set; }
}
Now when you run the application, and click on the button, you will see the values getting appending to the table as below -
Alternatively you can use AJAX form as shown below.
AJAXFORM Solution
Say you have Index as below -
#model MVC.Controllers.Person
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "productList" }))
{
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
}
<div id='productList'>
#{ Html.RenderPartial("itsme", Model); }
</div>
Which will hit Submit action and in turn we get a partial view -
public ActionResult Submit(Person p)
{
p.Name = p.Name + " Its me";
return PartialView("itsme", p);
}
And the partial view is simple which display the name -
#model MVC.Controllers.Person
#if (Model != null)
{
#Html.LabelFor(p => p.Name, Model.Name)
}
Finally the output -

If you don't want to return Partial View then you have to use a client side code to accomplish this. There are several options. You could review jTempaltes and jQuery Templates as an options. But if you won't call more than once this Ajax I would recommend you to return Partial View.

Related

Ajax passing data to ASP.NET controller

I'm attempting to run an ajax request on my ASP.NET web app where I pass a search term and receive some data back
<div class="form-group">
<input type="text" id="orgSearch" placeholder="Search organisation by name..." class="form-control" name="search" autocomplete="off" data-controller="#Model.ControllerName" data-target-property="#Model.LookaheadProperty">
</div>
<script>
$(document).ready(function () {
var form = document.getElementById("orgSearch");
form.addEventListener("keyup", function (event) {
event.preventDefault();
var search = document.getElementById("orgSearch").value;
$.ajax({
type: "GET",
url: "Organisation/Search?search=" + search,
success: function (object) {
console.log(object);
}
});
});
});
</script>
And then here's the method in my OrganisationsController.cs class
public class OrganisationsController : Controller
{
[HttpGet]
public async Task<IActionResult> Search([FromRoute] string search)
{
var items = await _organisationsService.SearchAsync(search);
return Ok(items);
}
}
However, when I try it the ajax call isn't even being made (It's generating a 404 error on the console log) and I can't work out how to pass the search parameter. Does anyone have any suggestions?
Fix ajax url from organization to organizations and add "/" in the beginning:
url: "/Organisations/Search?search=" + search,
your action then
public async Task<IActionResult> Search([FromQuery] string search)
{
......
}
You can also try to use [FromUri] instead [FromQuery]
And by the way, if your version Mvc supports attribute routing, it maybe better to change action to this:
[Route("~/Organizations/Search/{search}")]
public async Task<IActionResult> Search( string search)
{
....
}
in this case your ajax url:
url: "/Organisations/Search/" + search,

How to execute a controller method call in Javascript

Good afternoon!
I have the following controller action:
[HttpPost]
public ActionResult ShowComparisonResultSimpleViewFromJs(List<GetDocumentList_Result> documents,
GetAgreementNumberKktShiftInfo_Result infoResult)
{
ViewBag.DisplayName = CurrentUser?.DisplayName;
ViewBag.Documents = documents;
ViewBag.DocumentCount = Convert.ToString(documents.Count());
return View("ComparisonResultSimpleView", infoResult);
}
I also have an InputKktShiftView view that has a button click handler. In it I need to call the controller method specified above, as a result, the ComparisonResultSimpleView page is loaded.
Here is an example of a button click handler:
<script>
function OnClick(s, e) {
//Data for example:
var parameterModel = {
FnFactoryNumber: '1',//'9280440300664345',
ShiftNumber: 38
};
$.ajax({
type: 'POST',
url: '/TaxcomProblems/GetInputKktShiftJsonResult',
data: parameterModel
}).success(function(data) {
if (data.IsValid) {
if (data.InfoResult != null) {
var jsData = {
documents: data.Documents,
infoResult: data.InfoResult
};
//Here you need to call the /TaxcomProblems/ShowComparisonResultSimpleViewFromJs method
//$.ajax({
// type: 'POST',
// url: '/TaxcomProblems/ShowComparisonResultSimpleViewFromJs',
// data: jsData,
// dataType:'html',
// success: function(result) {
// var view = $("ComparisonResultSimpleView");
// view.html(result);
// }
//});
} else {
dxConfirm("Перейти на страницу выбора ККТ?")
.success(function() {
window.location.href = "/TaxcomProblems/ShowChoiceKktView";
});
}
}
});
}
Here is the code for my ComparisonResultSimpleView page:
#using System.Web.UI.WebControls
#using BonusProgramAPI.Tools
#model BonusProgramAPI.EF.GetAgreementNumberKktShiftInfo_Result
#{
ViewBag.Title = "Результаты для ККТ и смены";
ViewBag.agreementNumber = Model?.agreementNumber;
ViewBag.outletId = Model?.outletId;
ViewBag.fnFactoryNumber = Model?.fnFactoryNumber;
ViewBag.openDateTime = Model?.openDateTime.ToString("dd-MM-yyyy hh:mm:ss");
ViewBag.shiftNumber = Model?.shiftNumber;
}
<script>
function OnBtnGetKktInfoClick(s, e) {
pcKktInfo.Show();
}
</script>
#Html.DevExpress().FormLayout(settings =>
{
settings.Name = "rootLayout";
settings.Items.AddGroupItem(group =>
{
#* some code *#
}
}).GetHtml()
#* PopupControls: *#
#{
Html.RenderPartial("PopupControlKktInfoPartialView");
Html.RenderPartial("PopupControlShiftInfoPartialView");
}
Question: How do I call the ShowComparisonResultSimpleViewFromJs method of the TaxcomProblems controller so that the ComparisonResultSimpleView page displays?
P.S.: If I use ajax, then I call the specified method correctly (all data is transferred to it correctly), but the specified page is not displayed, and the current page remains.
Ajax post will not refresh the page. You have to do it by yourself. Also you are sending the full page from the ShowComparisonResultSimpleViewFromJs action with the following code:
return View("ComparisonResultSimpleView", infoResult);
What you can do is make the ShowComparisonResultSimpleViewFromJs action return partial content (html) instead of full page content. And then add the returned data in a div on the success method of the ajax call.
To return partial view write:
return PartialView("~/views/ComparisonResultSimpleView.cshtml", infoResult);
Also in the javascript codes note that the element selector is missing a class or Id notation. You can simply write:
$("#ComparisonResultSimpleView").html(result);
Your jquery selector is attempting to get the element
<ComparisonResultSimpleView></ComparisonResultSimpleView>
from here
success: function(result) {
var view = $("ComparisonResultSimpleView");
view.html(result);
}
Do you mean to select the element with id = ComparisonResultSimpleView ?
<div id="ComparisonResultSimpleView"></div>
You will need to add "#" to your selector like so:
success: function(result) {
var view = $("#ComparisonResultSimpleView");
view.html(result);
}
Want to know if the selector is correct?
Run the following line in your page's browser console
$("#ComparisonResultSimpleView").length; // greater than zero means the number of elements matching selector. Zero means no match.

C# Ajax - PartialView replacing whole page

I have a button and a droplist, when I press the button first my partialView is normally replaced.
But when I change an element in the list first and THEN I press the button, my whole page is replaced by my partial.
I checked around and saw that the jquery.unobtrusive was solving that issue for a lot of people but it was already included on my project.
Droplist :
$(document).on("change", ".RefreshList", function () {
$.ajax({
type: "POST",
url: "#Url.Action("RefreshList", "Feuillet")",
data: $("#form0").serialize(),
success: function (response) {
$('#header').html(response);
},
});
});
Controller :
[HttpPost]
public ActionResult RefreshList(CreationModificationFeuillet model, string actionName)
{
return PartialView("~/Views/Feuillet/CreationModification/Partial/Generale/PartialHeaderCreation.cshtml", model);
}
Button :
$("button[value='ContractSearch']").click(function () {
$("#modalMessage").modal('show');
$("#form0").attr("action", "#Url.Action("Creation" + Model.TypeProduit, "Feuillet")").attr("data-ajax-success", "AjaxFunction").attr("data-ajax", "true").attr("data-ajax-update", "#header").attr("data-ajax-mode", "replace");
});
Controller :
...
case "ContractSearch":
// doStuff
return PartialView("~/Views/Feuillet/CreationModification/Partial/Generale/PartialHeaderCreation.cshtml", model);

Asp.net MVC-5 working with bootstrap toggle switch

I am working on asp.net MVC 5, referring to my question i have added a bootstrap toggle switch in my page, the razor syntax is bellow
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>
}
This razor syntax is placed in a partial view and is called in a layout
The generated Switch button is as follows
Now, i want to pass this On or Off value(string) to my action method.
For start i have placed a javascript event function and which simply shows me the alert box displaying On or Off with respective switch condition
My script is as follows
<script>
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
alert("ON");
} else {
alert("Off");
}
}); </script>
For passing this On or Off i have searched many articles and found that ajax call is used for this purpose so i placed a ajax call in my if and else condition
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "On"}',
success: function (data) {
alert(data);
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "Off"}',
success: function (data) {
alert(data);
}
});
}
Bellow is my action method
public ActionResult MultiGraph(string search, string start_date, string cmdName , string End_date,int? page)
{
// i want to pass On or Off values based on switching in my string cmdName
}
Is there any other way rather than ajax call to do it? Or what should i do in my ajax call ?
Updated Code
In my script i have done the following
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
//alert("ON");
var data = { cmdName: "On" }
} else {
//alert("Off");
$.ajax({
url: '#Url.Action("MultiGraph")',
data: data,
});
}
});
See the bellow images
Getting null in cmdName
I am unable to pass them, i must be missing some thing which i don't know
Any help would be appreciated

Passing values from javascript to an MVC controller function when button is clicked

I have an Html Button and a razor EditFor textbox. this is to add something to a database. However, i want this particular button to call a function to get information from a webservice (IMDB) in order to fill in the rest of the information. Here is what I have for the Razor Portion:
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
I want to take this value and when the 'IMDB' button is clicked, i want to call the service to get the JSON. Heres my button:
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="IMDB" value="IMDB" class="btn btn-default" onclick="AjaxDisplayString();" />
</div>
</div>
And here is my javascript on the page:
<script>
function AjaxDisplayString() {
$.ajax({
url: #Url.Action("CallIMDB"),
method: 'GET',
success: function(data) { alert(data); }
});
}
</script>
This never calls my controller function. The page does nothing. Here is my MVC controller function that is supposed to be called
public ActionResult CallIMDB(string title)
{
var client = new WebClient();
var json = client.DownloadString("http://www.omdbapi.com/?t=" + title.Replace(' ', '+') + "&y=&plot=short&r=json");
var search = System.Web.Helpers.Json.Decode(json);
return search;
}
So, to sum up. I am trying to take the Title value from my razor for editor field and pass it into the controller function to get the JSON back from IMDB web service. However, the page does nothing, and the controller function is never called.
In order to take the "title" value, change your script like this:
<script>
function AjaxDisplayString() {
var action = '#Url.Action("CallIMDB")'; // action must be between quotes
var title = $("#Title").val(); // get the "Title" from input text
var url = action + "?title=" + title; // get the complete url with route values
$.ajax({
url: url,
method: 'GET',
success: function(data) { alert(data); }
});
}
</script>

Categories

Resources