Send complex object from view to MVC action as none ajax call - javascript

I'm working on an ASP.NET MVC web application.
There is a view with a bunch of search filters and there is also a grid in the middle of the page that represents the result of the search.
End-user set value for the search filter and when search button clicked an ajax call returns the values that will rebind the gird.
every row in the grid represents 'ItemId' and 'version' which could be selected by the checkbox.
At the end when the user clicks on "Detail report" we need to redirect the user to another page(view).
I need to pass the selected search filters and the grid selected rows values as an array like this (ItemIds[] and Versions[]) to the "Detail" action.
So, to make the question clear. I need to pass the below values to the action :
search filters
ItemId array
Version array
Unfortunately, I can not pass the parameters to the action. I got null
I can not call the action as ajax call When i use
View (Index.cshtml)
function prepareSelectedInfos() {
var formValues = $('#form').serializeFormToObject();
var gridValues = GetGridSelectedValues();
var dto = {
FormFilters: formValues,
ItemIds : gridValues.ItemIds,
Versions : gridValues.Versions
}
return dto;
}
$('#lnkDetailReport').click(function () {
var gridValues = GetGridSelectedValues();
var url = '/Report/Controller/Detail/';
var dto = prepareSelectedInfos();
window.open(url + dto, '_blank');
});
Controller
public ActionResult Detail(ModelVersionStatisticalDetailDto data)
{
//create a ViewModel according to the incoming data
var viewModel = ;
return View(viewModel);
}
Model
public class ModelVersionStatisticalDetailDto
{
public ModelVersionStatisticalReportDto FormFilters { get; set; }
public int [] ItemIds { get; set; }
public string[] Versions { get; set; }
}
I need to have the view prepared values in the Detail action

To the best of my recollection, it is not possible to perform a redirect after having post a complex object in ajax call (with the same posted parameters).
In order to perform your desired operation, you can choose a solution from below.
Use query strings in your Detail action and perform a simple post action instead of ajax call
Try to replace the response of Detail action with Partial View
If you are seeking a client side solution, you can assist from localStorage object (a tricky solution). You can store the required data in a localStorage object and pass the key to the controller. In the target page, use the key in order to fetch the data stored in storage. Do not forget to clear it after the process. https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/

Related

on page load call controller method using data from query string

Is it possible to retrieve query string data on page load using javascript?
Let me explain my sample project in steps::
I have a view page showing tabular data. On button press, it retrieves id of the row and calls javascript function.
This javascript function, getDetails(id) has to call another view page, say Application.cshtml.
I have to pass the value of id and a variable message to this view page Application.cshtml.
I am trying to pass this as query string.
Now in this view page Application.cshtml, I have to retrieve the value of id and call contoller method to show the details of the id on page load.
Is it possible to do using javascript?
function getDetails(id)
{
var message = "testing";
var id_ = id;
window.location = "/FirmModels/Application/" + id_;
}
My problem is how can I retrieve the value of id and call controller method on page load using javascript in Application.cshtml?
Your question is a bit unclear but as far as I understood this question you can do this in two ways.
Assuming that you have something like this in your JS file.
window.location = "/Controller/Application?id= " + id_;
In the first method, the View inside your Controller will look like this
public ActionResult Application()
{
string id= Request.QueryString["id"];
//Do your operations here
return View();
}
The second way to do this to pass the id as a mandatory parameter to the view.
public ActionResult Application(string id)
{
return View();
}

Laravel - search form with filters and old input

I'm developing a search form with filters, e.g. choose a gender from this list, choose an area etc., where these filters should be applied dynamically to the search query. The form submits with a post request in a controller. My question is now: How do I return the query result from the db to the search page, keeping the same, pretty url, and in addition return the old input for prepopulating the form with old data?
Regards.
EDIT:
I have tried something like this:
public function advancedSearch()
{
$users = Session::get('users');
return View("find-match.show", compact("users"));
}
public function getUsersAdvancedSearch(Request $request)
{
$users = User::select();
//Only active users excluding own profile.
$users->where('is_activated', 1)
->where('id', '<>', Auth::user()->id);
//Add gender.
if($request->has('form_genders'))
{
$users->whereIn('gender_id', $request->form_genders);
}
//Get matching users.
$users = $users->Paginate(self::paginate);
Session::put('users', $users);
return redirect()->route('match.advancedSearch')->withInput();
}
Use a Resource Controller and the "old" function of laravel to keep old post data for re population, and use the same url
https://laravel.com/docs/5.6/controllers#resource-controllers
https://laravel.com/docs/5.6/requests#old-input

Reload part of the page on button click, Refresh whole page on new URL

I am writing a single page Spring MVC application.
Requirements:
I want it to change the state of the page according to the URL that is entered.
I want it to change the state of the page on a click of a button.
Example use cases:
If I enter a URL "my.site.com/", I want only my site skeleton to be loaded, with no data for the User. (User is an object in my model).
If I enter a URL "my.site.com/users/John", I want the data for "John" to be displayed (the page can be reloaded).
If I enter string "John" in a textbox, and hit button Go!, I want only the part of the page displaying user data to be refreshed and not the whole page reloaded.
Design Question:
I understand that for 1) and 2) I would need to return a new ModelAndView object, and for 3) I could use AJAX. This probably implies I would need three controller methods.
What I don't know is how to avoid conflicting URLs between the MVC and AJAX controller methods, and how to actually then call my AJAX controller method from Javascript, and not the ModelAndView controller method.
Code Example:
What I would need is something like this, except that this, of course, causes conflicting URLs.
/*
* Default view.
*/
#RequestMapping(value = "/users")
public ModelAndView displayDefault() {
return new ModelAndView("userdisplay_default.jsp");
}
/*
* View for a specific user.
*/
#RequestMapping(value = "/users/{username}")
public ModelAndView displaySpecific(#PathVariable(value = "username") String username) {
User user = new User(username);
return new ModelAndView("userdisplay_specific.jsp", "Specific User", user);
}
/*
* AJAX controller method.
*/
#RequestMapping(value = "/users/{username}", produces = "application/json", method = RequestMethod.GET)
public #ResponseBody User getTime(#PathVariable(value = "username") String username) {
return new User(username);
}
In Javascript I would then fetch the POJO like this:
// obtain user
var user = $('#user_input').val(); // this is a text input
$.getJSON("/users/"+user, function() {
//...
});
NOTE: My way of trying to achieve that could be wrong // insufficient // not optimal, so please feel free to also suggest some other way on how to do that.
Could you please give me an explanation along with a code example how what I need should be accomplished?
You can make different methods for your controllers.
For example:
#RequestMapping(value = "/users") and #RequestMapping(value = "/users/{username}") - there are GET methods. But for AJAX make controller with POST:
#RequestMapping(value = "/users/{username}", produces = "application/json", method = RequestMethod.POST)
And JS will be smth like this:
// Send the request
$.post("/users/"+user, data, function(response) {
// Do something with the request
});
Another advice (if it's possible in your situation) - rename url for your rest. E.g. add word api into the url.

Variable not being set when using a C# property in an MVC view

i'm sorry if its a newbie question but can anyone tell me why can't I set a value of a var to a c# property ?
i am trying to find a way to use the value to retrieve some model properties & do a calculation ....
#using System.Collections
#using System.Runtime.Serialization
#using CarRentalMVCApp.Models
#model CarRentalMVCApp.Models.Rentals
#functions {
public string selection { get; set; }
public decimal Price { get; set; }
}
#{
ViewBag.Title = "Create";
}
<script>
function select() {
var $el = $("#selectedCar");
var selected = $("#selectedCar option:selected").text();
$el.on("change", #selection = selected);
alert(#selection);
}
function Rental() {
var choice = select();
#foreach (var car in ViewData["availableCars"] as IEnumerable<Vehicles>)
{
if (selection != null && int.Parse(selection) == car.מספר_רכב)
{
Price = car.עלות_ליום_השכרה;
}
}
if (firstDay != null && lastDay != null) {
var rentalData = {
price: #Price,
firstDay: $("#beginRental").val(),
lastDay: $("#endRental").val()
}
alert(rentalData);
}
}
</script>
the #selection always equals 0 and ones I try to set it with another veriable like so:
#selection = selected;
it remains 0 !!!
I also cant understand why I can't use any type of javascript variable if the # sign is involved , would appresiate an explanation if you have the time or the links to help .....
MVC views are simply templates; there is not any sort of interoperation between C# and JavaScript. Rather, your C# variables simply cause text replacement. Therefore, these lines:
$el.on("change", #selection = selected);
alert(#selection);
...simply take the C# selection value and perform a substitution. So if selection is set to "foo" in the C#, the JavaScript that is output is:
$el.on("change", foo = selected);
alert(foo);
The event handler syntax for the change event is incorrect even if this did work. Plus, you cannot have JavaScript assign a value to a C# property. Rather, JavaScript will have to submit a form or perform an AJAX request to send data back to the server for processing, where it's handled by an MVC controller.
You cannot set a C# variable value in your client side code like the way you tried. Because when razor executes, it executes the C# code in it (at server) and the result of that (which could be string) will be send to the client to render the markup needed for the page.(Check the view source of the page).
So if you need to use this in your server code, you need to make an ajax call and send it to server
So if you want the price of the selected item value, make an ajax call to your server and send the selected option value and using that calculate the price and return it.
var selected = $("#selectedCar option:selected").text();
$.get("#Url.Action("GetPrice","Home")"?id="+selected ,function(res){
alert("Price of selection" + res);
});
Assuming GetPrice accepts a parameter with name id and returns the price
public ActionResult GetPrice(int id)
{
// based on this id, Get the corresponding price
decimal price = 100.0M; //replace with your value from db
return Json(price,JsonRequestBehavior.AllowGet);
}
Short answer:
The # means that it's server code, not client code. It gets executed before the page is sent to the user. Once the server finishes and the user gets the page, javascript code get executed.

Is it possible to check the textbox value in MVC without clicking submitting/postback

I am new to MVC.
I am having one form, let's call this as Registration Form. In that I have 10 textboxes(id,name,address..etc)
Once user enters the Id -I have to check in DB it's already available or not and then i need to display status.
Is it possible in MVC?? without Clicking on submit button ??
Thanks in Advance.
Yes it is in fact not hard to achieve this. You can use RemoteAttribute on the property of your model that you want to be validated asynchronously on the server, in your case it is id.
http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.118).aspx
// model
public class MyModel
{
[Remote("ValidateId", "MyController")]
public string Id { get; set; }
}
// controller
public class MyController
{
public ActionResult ValidateId(string id)
{
// action will be invoked when you change value in the browser.
// you have to return a string that contains an error if the id fails validation.
// or true if the id is valid.
// this is in case id is valid
// return Json(true, JsonRequestBehavior.AllowGet);
// this in case id is not vlaid.
// return Json("id is not valid", JsonRequestBehavior.AllowGet);
}
}
Take a look at this also:
http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

Categories