Jquery autocomplete httppost actionresult not loading after ajax post - javascript

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();
}
});

Related

MVC reload page after selecting a value from the drop down list

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

JQuery not calling HttpPost method on my controller. How can I fix this, or what could be going wrong?

I have a special case where I need to have a grid with an "Add New Record" row, that exists within an MVC form.
Since I can't submit the new record details, without submitting the entire form, I decided to make the record submit button call a Javascript method that should POST the data to a method on my controller. In short, here is an example of what I'm doing. The code below is copy-and-pasted from my project, with only minor modifications for brevity.
...
<table>
CODE HERE FOR MY GRID...
</table>
...
<input class="data_field" id="MainSession_Name" type="text" />
<input class="data_field" id="MainSession_Type" type="text" />
<button id="btnAddMainSession" class="button" onclick="SubmitMainSession()" type="button">Add Session</button>
...
<script>
var SubmitMainSession = function()
{
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post(
{
url: "/Session/Add",
data: data,
callback: function(res, status)
{
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
}
});
}
</script>
My intent is simple. After the user enters new details for a session, they will click on the Add Session button. JQuery will make a POST request passing my data to my page controller.
Here is an abbreviated variation of my controller:
//Index that initially loads the data.
public ActionResult Index(int id = -1)
{
SessionModel sm = new SessionModel(id);
sm.CanEdit = true;
return View(sm);
}
//The containing model manages a HUGE form,
//across multiple BootStrap.js tabs. We save
//all other, non-sub-record related deets here.
public ActionResult Submit(SessionModel model)
{
model.Save();
return Redirect(Url.Content("~/"));
}
//Since there are multiple grids, I need to
//have a way to add new Session records.
//This is my first attempt at trying to
//create a POST method on my controller.
[HttpPost]
public string Add(AddSessionObject data)
{
//If I can ever get here, I'll save the data.
return "OK";
}
public class AddSessionObject
{
public string Name;
public string RecType;
}
What I'm experiencing is that when I make the $.post(...) call in JQuery, MVC always calls the Index(...) method, rather than the Add(...) method. What am I doing wrong?
try using this syntax:
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post("/Session/Add", data, function(res, status) {
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
});
https://api.jquery.com/jquery.post/

ASP.NET MVC ActionResult POST without Submit

So I am very new ASP.NET MVC, I took an intro ASP.NET months and months ago, and have unfortunately forgotten nearly everything :(
I have been given a task to add a lookup button to a page that takes in a username from a textbox and verifies whether or not that username is valid.
I have spent hours and hours trying to get it to work. Unfortunately what i realllyyy need to do is sit down for a few weeks and re-teach myself and learn javascript, jquery, asp.net mvc. I am going to learn it all, but this assignment is to small and specific to spend weeks learning languages and frameworks just to begin solving.
Here is where i'm at:
Structure of Controller:
public class NewUserRequestController : Controller
{
// GET: NewUserRequest
public ActionResult Index()
{
return View(new NewUserRequest());
}
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult LookupLDN(ITFormsLibrary.NewUserRequest req)
{
//Code that Verifies user etc
return View(req);
}
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Submit(ITFormsLibrary.NewUserRequest req)
{
//Code that handles submission validation & errorvalidation
return View("Index", req);
}
}
Now in the view, I have tried messing around with:
#using((Ajax.BeginForm("LookupLDN", "NewUserRequest", FormMethod.Post, new AjaxOptions { UpdateTargetId = "NewUserIfo"}, new { #class = "form-inline", role = "form" }))
Only to discover I can't nest forms.
I have tried:
#Ajax.ActionLink("Lookup", "LookupLDN", "NewUserRequest", new { Model},null, new { #class = "form-inline", role = "form" })
and
#HTML.ActionLink("Lookup", "LookupLDN", "NewUserRequest", new { Model})
both of which return 404 for some reason.
I have also tried:
<input type="button" value="Lookup" onclick="return lookupLDN()"/>
But, I don't know how to construct a javascript statement to handle an asynchronous POST? - Should I even be trying to POST?
If any of you understand what I am trying to accomplish and can provide help, I would be extremely grateful. thank you!
How about JSON.
EDITED as per Tommy's comment. Use POST instead of GET.
It should be a POST method because you are sending data to the server
and asking it to take action on that data (POST) and not just asking
the server to give us information without sending it anything (GET).
With POST, you can add checks around CSRF tokens, don't have to worry
about the Googlebot doing something it shouldn't, etc.
HTML (VIEW)
<input type="button" id="btnLookupUser" value="Lookup" />
JAVASCRIPT
$(document).ready(function () {
$('#btnLookupUser').click(function () {
var vUsername= $('#txtUserName').val();
if (vUsername.trim() == '') {
return;
}
else
{
//URL to your JSON method. (here I suppose you have a LookupUser action method. Change application path the way it works for you.)
$.ajax({
url: applicationPath + '/LookupUser',
type: 'POST',
dataType: 'json',
data: { userName: encodeURIComponent(vUsername.trim()),
cache: false,
success: function (result) {
//Do your logic based on the result.
switch (result) {
case true:
break;
default:
break;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
})
});
});
CONTROLLER
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LookupUser(string userName)
{
//Your logic
return Json("Whether is valid or not"); //You can as well deny GET here.
}

Returning view from jQuery AJAX get operation

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>

How to pass values from view to controller using jquery function in asp.net mvc3

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){
});

Categories

Resources