I'm trying to make an asynchronous jQuery get to an MVC Action to return a view. For some reason, although it accesses the action, it does not render the view.
This is the jQuery:
function showArchive(url) {
var moreRecentThanDate = $("#chooseDate").val();
$.get(url, { moreRecentThan: moreRecentThanDate });
}
and this is the action :
[HttpGet]
public ActionResult ShowArchive(DateTime moreRecentThan)
{
List<NewIndexViewModel> model = Service.GetArchives(moreRecentThan);
ViewBag.IsArchive = true;
return View("Index", model);
}
PS: I call this jQuery from an ad-hoc modal popup;
You should attach the result in somewhere using a syntax like that:
$.get(url, { moreRecentThan: moreRecentThanDate }).done(function(data) {
$('.result').html(data);
)};
When in doubt, check the jQuery documentation, get(), the second last example is what you want, I believe..
$.get(url, { moreRecentThan: moreRecentThanDate })
.done(function(data) {
$('#myElem').append(data);
// or $('#myElem').html(data);
});
Jquery Part
$.get( url, { moreRecentThan: moreRecentThanDate }, function(data) {
// callback or response
$('#details_Div').replaceWith(data);
});
where the user controller has an action named details that does:
public ActionResult Details( int id )
{
//create a model
return PartialView( "UserDetails", model );
}
PartialView is important here.
This is assuming that your partial view is a container with the id detailsDiv so that you just replace the entire thing with the contents of the result of the call.
UserDetails partial view
http://evolpin.wordpress.com/2011/04/26/asp-net-mvc-partial-view-and-ajax-real-world-example/
<div id="details_Div">
<HTML will be replaced once the ajax is completed>
</div>
Related
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.
I have a working solution, but I don't know how to reload the page after a certain ID is selected from the drop down list. My list is being populated from the DB. When I select it, I can see the ID and the corresponding data for it. However, there is no change on the screen.
Controller class:
public ActionResult Index()
{
var model = test.getStuff();
ViewBag.IDs = new SelectList(test.getID(), "", "ID");
return View(model);
}
[HttpPost]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
return View(que);
}
View Class:
#Html.DropDownList("ID", ViewBag.IDs as SelectList)
$(document).ready(function () {
$("#ID").on("change", function () {
var selectedId = this.value;
var url = "/Sample/getDataBySelectedID";
$.ajax({
method: "POST",
dataType: "json",
url: url,
data: {
selectedId: selectedId
}
});
});
});
How would I be able to reload the page with the selected value and its corresponding data?
Any help would be appreciated!
Thank you.
in getDataBySelectedID return view similar to Index that is construct model with filter applied and return View(model)
Since you want to reload the page after dropdown selection changed, you should handle change event to redirect with query string like this:
$("#ID").on("change", function () {
var selectedId = $(this).val();
window.location.href = '#Url.Action("getDataBySelectedID", "Sample")' + '?selectedId=' + selectedId;
});
Take note that window.location.href uses HTTP GET method, hence the target action must use [HttpGet] instead of [HttpPost]:
[HttpGet]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
// don't forget to repopulate ViewBag from SelectList here
return View("Index", que); // return same page with different model contents
}
Make sure getHello() method return type is the same as getStuff() method to avoid passed model item related exceptions.
But if you want to submit the form and show it again afterwards, then use $('form').submit() instead:
jQuery
$("#ID").on("change", function () {
$('form').submit();
});
Controller
[HttpPost]
public ActionResult getDataBySelectedID(ViewModel model)
{
// do something
return View(model);
}
no need to use ajax in your case
just do a
window.location.href = "/Sample/getDataBySelectedID?selectedId=" +selectedId;
in your onchange function, and in your view return it as
[HttpGet]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
return View("~/Index.cshtml",que);
}
hoping "que" is the same kind of model like you are using on your Index function
So i've been searching stack for hours and cannot seem to find a solution. I'm trying to implement a basic jquery autocomplete, but when i click/select the item in the autocomplete dropdown to send me to a new page, my httppost actionresult isn't returning the view. It runs through the httppost controller fine (all paramaters are passed,queries run, models are passed to views, etc). I'm pretty sure it's due to the window.location.reload(); in my ajax post, but can't seem to figure this one out. I also tried window.location.href = link; but that wasn't working either. Please help :(
JS
$("#queryTypeInput").autocomplete({
source: "/Dashboard/EnterMatterFormAjax/",
select: function (event, ui) {
var inputVal = ui.item.value.substring(0, 10);
$.ajax({type:"POST",
url:"Dashboard",
data:{ queryType: queryTypeval },
success: function (result) {
window.location.reload(); //this is where i think the issue is
}
})
});
EnterMatterFormAjax Controller (WORKING FINE)
public JsonResult EnterMatterFormAjax(string term)
{
var termReq = Request["term"];
var termReq2 = "";
if (termReq.All(char.IsDigit))
{
termReq2 = termReq + "%";
}
else
{
termReq2 = "%" + termReq + "%";
}
var ajaxMatterData = GetAjaxMatterData(termReq2);
return Json(ajaxMatterData, JsonRequestBehavior.AllowGet);
}
Index Controller (WORKING FINE)
[HttpPost]
public ActionResult Index(string queryType)
{
...goes through code logic...
return View();
}
I just resubmitted my form after the autocomplete select instead of using the window.location.href as #KarthikMR mentioned. I would have had to change around my controller actions, so i just took the simplest road. #KarthikMR suggestion did work though when i changed my actions, so this is a viable option! updated js below:
$("#queryTypeInput").autocomplete({
source: function (request, response) {
$.post("Dashboard/EnterMatterFormAjax", request, response);
},
select: function(event, ui){
$("#queryTypeInput").val(ui.item.value);
$("#enterMatterForm").submit();
}
});
I initialize a property within the Controller's Constructor.
public BookController()
{
SessionProvider.SessionLoadSceanrio = false;
}
I have an Action Method which reset the property again on a button click event.
public ActionResult LoadScenario(int bookId)
{
SessionProvider.SessionLoadSceanrio = true;
// remaining code
return Json(ScenarioId, JsonRequestBehavior.AllowGet);
}
Following javascript code is in my view which is called when the button is clicked.
var BookHandler = {
$("#btnLoadScen").click(function (e) {
$.ajax({
url: "#Url.Action("LoadScenario", "Book")",
dataType: 'json',
type: 'POST',
data: {
'bookId': BookHandler.getBookId()
},
success: function (response) {
var scenarioId = response;
var isLoadScenario = "#Portal.Presentation.Web.Planning.MVC.App_Start.SessionProvider.SessionLoadSceanrio";
//otherproperties
window.open("#Url.Action("Index", "BookScenario", new {loadScenario = "_loadScenario"}).replace('_loadScenario', isLoadScenario), tabId);
},
error: function () {
}
});
});
}
My problem is when I click the button, value of property changes in the Controller. But it doesn't change in my javascript code.Please see the screen capture of the developer tool.
does Anyone has a clue on this?
You are using the razor syntax. then initially page loaded , values are set, and these values are string , not a variable anymore. then you can't get session value updated again.
please get session value from an AJAX call and set to your variable.
The code below will only be evaluated once you get the view from server and will not be re-evaluated after your ajax call.
var isLoadScenario = "#Portal.Presentation.Web.Planning.MVC.App_Start.SessionProvider.SessionLoadSceanrio";
In order to do what you intended, you will need to return SessionLoadSceanrio in your response.
You can do it like:
public ActionResult LoadScenario(int bookId)
{
SessionProvider.SessionLoadSceanrio = true;
// remaining code
return Json(new {ScenarioId, SessionLoadSceanrio = SessionProvider.SessionLoadSceanrio}, JsonRequestBehavior.AllowGet);
}
I have to pass values from view to controller, controller having action method that will call webmethod to set values into database. how can i do that?
need not to create a view of using model.
I have a view that get the values from database and having one link that is comment. on click of comment one textarea box will open and after providing some input. will click on ok button.
on click of button ok i am calling
$('a.comment').livequery("click", function (e) {
var getpID = $(this).parent().attr('id').replace('commentBox-', '');
var comment_text = $("#commentMark-" + getpID).val();
//alert(getpID);
//alert(comment_text);
if (comment_text != "Write a comment...") {
//$.post("/Home/SetComment?comment_text=" + comment_text + "&post_id-= " + getpID, {
}, function (response) {
$('#CommentPosted' + getpID).append($(response).fadeIn('slow'));
// $("#commentMark-" + getpID).val("Write a comment...");
$("#commentMark-" + getpID).val();
});
}
now what can i do to get getpId and comment_text values to the controllers SetComment action?
You could use $.post method to send them as an AJAX request:
var url = '#Url.Action("SetComment", "Home")';
var data = { commentText: comment_text, postId: getpID };
$.post(url, data, function(result) {
// TODO: do something with the response from the controller action
});
which will post to the following action:
public ActionResult SetComment(string commentText, string postId)
{
...
}
you can use jquery post http://api.jquery.com/jQuery.post/
$.post("/Home/SetComment",{comment_text:Text,postId:PostId},function(data){
});