What is the best way to put my variable in an Ajax request function - ajax

Context: I am working on a Spring WEB MVC app using JSP for the view.
In my JSP page i have an input text field which in fact is a jquery daterange picker:
<input type="text" name="daterange" value="01/01/2017 - 01/31/2017" />
I thought in this ajax function I can retrieve the value of my input daterange and pass it to var daterange? like this:
function filterByDate() {
$.ajax({
url : 'outbatch',
data : ({}),
success : function(data) {
var daterange = document.getElementById("daterange").value();
}
});
}
And this is my Controller (i did not pase everyting it is too long don't look at the return null i just put it for showing) method who will update my batch and get the information from my model:
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public String updateEblnotif(Model model) {
String out_path = env.getProperty("notif_out");
List<Doc> doc_list = unmarshal(out_path, "LETTERS");
System.err.println("jbb*********" + doc_list.size());
Set<String> formname_set = new HashSet<>();
`......
return null`}
My question is: Where do I have to pass the variable in my Ajax function call to my Controller? I know that, if I am not mistaken there are several other option parameters that I can pass into an Ajax function like 'data' , 'datafilter' , 'datatype' ? Which is the best way for requesting Dates assuming in my model those are Java Date Objects
Note: I am a very Junior Developer this is my first project. My model uses a DAO with hibernate to map into the database.
Thanks to all of you for your help!

first of all you should get the value of the parameter in client side so to that you simple have to add id attribute to the tag so that your getElementById could be useful, try this :
<input type="text" name="daterange" id="daterange" value="01/01/2017 - 01/31/2017" />
now let's suppose that your function is responsible on retrieving the desired value and send it as parameter to the server side with AJAX, so it's simple :
function filterByDate() {
var daterange = document.getElementById("daterange").value();
$.ajax({
url : 'outbatch',
data : {"daterange":daterange}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
alert(data); //here you will see an alert displaying the callback result coming from your spring controller
}
});
}
now we sent the daterange to the controller , so we have to get it back there : to do that you simply can try the following approach :
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public #ResponseBody String updateEblnotif(Model model,#RequestParam("daterange") String daterange) {
//so here you're ahving the daterange parameter in controller , if you want to display it in the alert , you can send it in the return like this,
String date = "the daterange is "+daterange
return date;
}
i hope it was clearly for you.

Related

Controller action method call have the parameter as NULL while calling javascript in MVC3

I use MVC3.
I have `
function userLocation_change()
{
var text = $("#userLocation").val();
alert(text);
var url = '#Url.Action("GetAllLocations", "Home")';
var data = text;
$.post(url, data, function (result) {
});
}
`
Here is my controller action:
public JsonResult GetAllLocations(string userlocation)
{
///...some code...
return Json(..Something.., JsonRequestBehavior.AllowGet);
}
The problem is whenever the controller function is called "userlocation" parameter does have a NULL value. I want the data value would be passed to the controller action.
Could somebody plz tell me why this happens? Any update would be much appreciated.
Thanks.
You need to pass the parameter to the #Url.Action specifically via this overload method for Url.Action. You can use the RouteValueDictionary inline constructor with to instantiate.
Edit: realize now that you need that link to be populated at run time, but the Url.Action method generates the link at render time. I would suggest adding it to the query string and then reading it from the query string in your controller method. I suspect there is a more elegant way.. but I know this works.
something like: var url = '#Url.Action("GetAllLocations", "Home")?userlocation=' + $("#userLocation").val();
Modify your jQuery post function call as:
$.post(
url,
{ userlocation: text },
function(result){
....
});
This is because, you have to send data to the Controller's action method using JavaScript literal. You can view the full listing of different ways to call Controller's action using JavaScript here: http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
Your action has a string input parameter named userlocation, hence while sending the data to the action, you should specify this, like done in the code below.
Here I am using data: { userlocation: text},
function userLocation_change()
{
var text = $("#userLocation").val();
var url = '#Url.Action("GetAllLocations", "Home")';
$.ajax({
url: url,
type: 'POST',
data: { userlocation: text},
success: function (result) {
}
});
}
Hopes this solves your null problem.

Write data from cotroller to view javascript

I need to get some data from a controller into the JavaScript in a view.
I have the following method:
private JsonResult GetSection()
{
string orderId = (orderService.GetOrder(UserSEssion)).Id.ToString();
return this.Json(orderId);
}
I have the following in the view:
<script type="text/javascript">
lpAddVars('page', 'Section', + GetId()+);
function GetId() {
$.getJSON("/Checkout/GetSection", null, function (data) {
someThing = data;
});
}
</script>
I would appreciate any help in how to do this.
Thanks
Is the orderId already part of your model? You would be able to just access it in the view via the model. If you need the approach you are using I would start by making the method public and you may need to put the http verb attribute on it as well HttpGet

Retrieve values from getJSON() call in jQuery

I have an ajax call in my jquery to my MVC controller:
$.getJSON('/mysite/controller/dosomething', { postId: id }, function (data) {
The 'data' that I am returning is in the form of a JsonResult, and consists of a simple custom object with 1 property called 'Message' and another property called 'Count'. Both of these values are assigned and I am returning them as follows (edited for brevity):
[HttpGet]
public JsonResult DoSomething(int postId)
{
var response = new MyAjaxResponseModel {Message = "Hello world!", Count = 66};
return Json(response, JsonRequestBehavior.AllowGet);
}
In my jQuery, I then want to be able to look at both values in the Json response, but I don't know the proper way to get at these values?
data.Message, data.Count in the callback you're passing to $.getJSON()? To inspect the structure of your data object, you can use console.log(data) (also, in that callback)

Route values disappeare in View .Net MVC3

I have simple controller:
public class TestController : Controller
{
public ActionResult Test(string r)
{
return View();
}
}
I have simple View Test.cshtml:
<h2>#ViewContext.RouteData.Values["r"]</h2>
#using (Html.BeginForm("Test", "Test"))
{
<input type="text" name="r" />
<button>Submit</button>
}
I have route rule in Global.asax:
routes.MapRoute(
null,
"Test/{r}",
new { action = "Test", controller = "Test",
r = UrlParameter.Optional }
);
I want to make such thing: user types route value in input, press submit and controller redirects him to page Test/value. But controller show just page with name Test everytime. ViewContext.RouteData.Values["r"] is empty too. I check in debug, Test action recieves user value of r correctly.
How can I realize my idea?
Thanks.
I'm super late to the party, but just wanted to post a solution for reference. Let's assume that this form has more than just a strong as it's input. Assuming there are other inputs, we can wrap up the inputs of the form into a class in our model, called TestModel whose properties maps to the id's of the form's inputs.
In our post, we redirect to the get, passing in the route values we need in the URL. Any other data can then be shuttled to the get using a TempData.
public class TestController : Controller
{
[HttpGet]
public ActionResult Test(string r)
{
TestModel model = TempData["TestModel"] as TestModel;
return View(model);
}
[HttpPost]
public ActionResult Test(string r,TestModel model) //some strongly typed class to contain form inputs
{
TempData["TestModel"] = model; //pass any other form inputs to the other action
return RedirectToAction("Test", new{r = r}); //preserve route value
}
}
You cannot do this without javascript. There are two types of methods that exist when submitting a <form>: GET and POST. When you use POST (which is the default), the form is POSTed to the url but all data entered in input fields is part of the POST body, so it is not part of the url. When you use GET, the input fields data is part of the query string but of the form /Test?r=somevalue.
I wouldn't recommend you trying to send user input as part of the path but if you decide to go that route you could subscribe to the submit event of the form and rewrite the url:
$('form').submit(function() {
var data = $('input[name="r"]', this).val();
window.location.href = this.action + '/' + encodeURIComponent(data);
return false;
});
As far as you are saying to post the form to Html.BeginForm("Test", "Test") you will be always posted back to the same page.
A solution could be to use an explicit Redirect to the action using 'RedirectToAction' (in view) or you can use javascript to change the form's action:
<input type="text" name="r" onchange="this.parent.action = '\/Test\/'+this.value"/>

gets called from separate controller (ASP.NET MVC3)

I'm trying to call an action in a separate controller with an actionlink.
The problem is that both the [HttpGet] and the [HttpPost] action gets called, and since the post-method returns the view from which the action is called, nothing gets displayed.
Get method:
[HttpGet]
public ActionResult View(int id, int index)
{
var form = formService.GetForm(id);
var pageModel = new PageViewModel();
var page = form.Pages.ElementAt(index);
ModelCopier.CopyModel(page, pageModel);
ModelCopier.CopyModel(form, pageModel);
return View(pageModel);
}
Post Method
[HttpPost]
public ActionResult View(PageViewModel pageViewModel)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Details", "Forms", new { id = pageViewModel.FormId });
}
var pageToEdit = pageService.GetPage(pageViewModel.PageId);
ModelCopier.CopyModel(pageViewModel, pageToEdit);
pageService.SavePage();
return RedirectToAction("Details", "Forms", new {id = pageViewModel.FormId});
}
How it's called from the View (from a view returned by another controller):
#Html.ActionLink("View", "View", "Pages", new { id = Model.FormId, index = item.Index-1 }, null)
What am I doing wrong here? I essentially want it to work as an update/edit function. And the view returned contains a simple form for the viewmodel.
An action link issues a GET request. You will have to implement some JavaScript function that captures the url and parameters, and dynamically creates and submits a new form with a POST method, or does an Ajax POST. You could write your own HTML Helper, to wrap this functionality, but the default functionality of clicking an <a> tag (which is what is generated by a Html.ActionLink) will issue a GET request.
I don't think you'll be able to use an action link - see this question
The options are to use jQuery to post data or swap to a simple form and submit

Resources