ViewModel current state to JSON - javascript

I have an issue with aps.net mvc project. I have a view where is set list of check boxes inside of begin form, then on submit appropriate fields are shown as a report. So I have to add a button to my view, where user is setting which fields he d like to see, so as he could save all checkbox values as a preset with its name.
I have model with a lot of nested models it looks like this:
public class EmployeeOverallReport
{
public List<PersonalData> ListOfPersonalData { get; set; }
public EmployeeOverallReportBool ColumnsNeeded { get; set; }
public EmployeeOverallReportFilters ModelFilters { get; set; }
}
I actually need ColumnsNeeded model, which has alot of bool properties for storing each checkbox value (true/false).
So on click I have to get current state of checkboxes and make a post with these model values.
I have been trying to serialize my form:
var data = $('#myForm').serialize();
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
I got JSON string but it was invalid and i could not deserialize it back.
Here is what I am trying to do now:
$("#savePresetButton").on('click', function () {
var url = "/Reports/SavePreset";
var data = #Html.Raw(Json.Encode(Model));
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
});
this code is using my viewModel with its properties, where all ColumnsNeeded properies are set to false, as it is by default and all user side changes in a view are not set to model yet, so as my form was not submitted and values were not changed.
How could I get current state of all checkboxes on user side?
Not doing it like :
var dataset = {
CategoryBool: $("#ColumnsNeeded_CategoryBool").val(),
NameBool: $("#ColumnsNeeded_NameBool").val(),
KnowledgeLevelBool: $("#ColumnsNeeded_KnowledgeLevelBool").val(),
SkillAdditionalInfoBool: $("#ColumnsNeeded_SkillAdditionalInfoBool").val(),
...
}
because I have more than 90 properties there..
I am sorry for this post, but posting some code is impossible due to count of properties inside the model.

Could you serialize the entire form and ajax submit the form itself?
see: Pass entire form as data in jQuery Ajax function

Related

ASP.NET MVC 5 best practise form submit

Description:
I have a form for user-friendly input:
But i can't submit form in this way, coz my model for this form action looks like:
public string Title { get; set; } // First input
public string Description { get; set; } // Second input
public string SportsmanId { get; set; } // Not used
public List<WorkoutExerciseParam> WorkoutExerciseParams { get; set; } // Items, combined from list items (show on form screenshot)
public SelectList AvailableSportsmans { get; set; } // Dropdown list
So, if I can't submit, I wrote JS code to construct and post consistent model:
$(document)
.ready(function() {
$("#submit").click(function() {
var exerciseList = [];
/* Assemble exerciseList from OL and UL items */
var title = $("input#Title").val();
var description = $("input#Description").val();
var sportsmanId = $("select#SportsmanId").val();
$.post('#Url.Action("Create", "Workout")',
{
Title: title,
Description: description,
SportsmanId: sportsmanId,
WorkoutExerciseParams: exerciseList
});
});
});
This code works fine, but I can't redirect after the action is done (like when I just submit the form):
Then, I rewrite JS code so, that it constructs a new hidden form with hidden input and submit it. But I don't know how to create the list of inputs (List from first code sample).
Question:
What is the best practice to submit data to ASP.NET Controller's Action throw JS that I can use RedirectToAction() and View() methods?
Do I need construct form (how can I do a list of objects) or how handle RedirectToAction() and View() method in JS?
You should be making a normal submit rather that ajax if you want to redirect (or be able to return the view and display validation errors if ModelState is invalid. There is no point using ajax, since ajax calls do not redirect.
You have not shown how your dynamically generating the inputs associated with your WorkoutExerciseParam collection, but they just need to be named correctly with indexers so that they will be bound by the DefaultModelBinder. The format needs to be
<input name="WorkoutExerciseParams[0].SomeProperty" .... />
<input name="WorkoutExerciseParams[0].AnotherProperty" .... />
<input name="WorkoutExerciseParams[1].SomeProperty" .... />
<input name="WorkoutExerciseParams[1].AnotherProperty" .... />
....
Your can generate this using javascript, but a better solution which gives you string type binding, client side validation for the dynamically added items and the ability to also delete items is to use the BeginCollectionItem() method as discussed in the answers to
Submit same Partial View called multiple times data to
controller?
and
A Partial View passing a collection using the
Html.BeginCollectionItem
helper

How to append Complex Data Type to View Model before submit of form post method

I am using Form Post method to submit data to controller in my MVC application.
My MVC Application controller method accepting ViewModel.
I have added new list of other viewModel and I want to pass the data to that newly added viewmodel.
Sample Code ( not fully executed )
Controller Existing Code
public ActionResult AddProduct(ProductViewModel productViewModel)
{
//some operation
}
public class ProductViewModel
{
Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();
}
//viewmodel
$('#ProductForm').submit(); //javascript form submit method
var ObjectList = new Array()
Now I have added List of Objects in Object List
I want to pass this list controller
You need to create hidden elements as per your complex data type
Consider following issue
If you need to post employee list with attribute like name etc then go through following code.
Your view Model something like
public class ProductViewModel
{
public IList<Employees> = new List<Employees>();
}
Javascript Code
var html = '<input type="hidden" name="Employees[0].Name" value="Employee1"/>';
html+='<input type="hidden" name="Employees[0].Designation" value="Des1"/>';
html+='<input type="hidden" name="Employees[1].Name" value="Employee2"/>';
html+='<input type="hidden" name="Employees[1].Designation" value="Des2"/>';
$('#ProductForm').append(html);
$('#ProductForm').submit();
You will get list of two records as (0 and 1 ) index.
You can use for loop and generate hidden html dynamically and append it before Form submit.
you need to define the list as property inside the ViewModel you are passing, by default modelbinder does not consider the fields like
Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();
you need to define the property Like
public IList<Branch_Product_TaxesViewModel> Branch_Product_Taxes { get; set; }

x-editable submit additional "array" to the total AJax POST data

I'm trying to add an array of object to the post data of a group of bootstrap x-editable in my jsp page.
I recover the data from a table, and build an array of object. After do that, I need to append this array to the list of the other value posted by the editables in the page.
I've an html table with id="user" and this code recover data from it and build the array of object. This is my code, that works and produces the correct object:
function recover_data() {
console.log("Starting recover");
var beneficiary_list = [];
$('.lav').each(function() {
var obj = {'company': $(this).attr('id'), 'num':$(this).text() };
beneficiary_list.push(obj)
});
console.log(beneficiary_list); //output to check array produced
return beneficiary_list;
};
this function is what I call from a save button, that launch my global submit retrieving data from all editable in the page and adding in the "params" the array returned from recover_data(), in this way:
jQuery('#data a').editable('submit',{
url:'test/prove/data_received',
params: function(params) {
params.beneficiary = recover_data();
return params;
},
success:function(resp){ ... }
})
but testing with Postman (Chrome) the produced output to POST, is without the array. Are submitted only the "editables" data, but no "beneficiary" field with array of that values adding. The missing field must be like
"beneficiary": [0: company: "1", num: "22" ..etc..]
How can I "append" to the produced POST data from a group of editables an array of objects, like that I've show?
Looking to this page is possible
Question on github x-editable page
I don't understand why don't works...I follow the example written on second post from vitalets, he wrote:
editable({
...
params: function(params) {
params.checked = ... //get array of checked values
return params;
}
});
To Explain better what I need: I've a Java Controller (servlet) that receive a modelView object (POJO) with several fields (that came from other editables in the page) and a field "ArrayList beneficiary" where Beneficiary is a small object of two fields "company" and "num"
public Class Beneficiary{
private String company;
private String num;
//then get e set methods..
}
instead, my POJO is like:
import java.util.ArrayList;
import Beneficiary;
public class Module {
private Integer id;
private String titolo;
private String companyRating;
private ArrayList<Beneficiary> beneficiary;
//get e set methods
In the console I obtain the correct object for that voice
but not in the post object that is like
instead I need that the produced output "beneficiaries" field to POST url is something similar to this example (found on internet)
How can I obtain a list of that object from my JSP page when submit?
Someone can help me?
params is an option for editable object, while you are using it as options for ajax call.
Your code should look like:
$('#data a').editable({
url: "/post"
});
and then the submit() (note selector for all of your editable objects):
$('.editable').editable('submit', {
data: {beneficiary: recover_data()},
success:function(resp){ ... }
});
Working fiddle. Check your console to see logs

Javascript array sending to asp.net MVC controller

I'm currently trying to develop a web app in which a user defines a set of points with coordinates on google maps, these points are stored on an array like this one:
mvcPolygon: new google.maps.MVCArray(),
Now I need username, password, etc. and submits it to the server. I'm pretty new with javascript and frontend development so I'm quite clueless here as to what is the way to go.
So currently I have the javascript code which is storing the coordinates and what I need is that when the user is finnished defining his polygon, and filling a form with username, password, email, etc. all this info gets sent to the controller as soon as the user hits the submit button.
The webapplication is currently being developed on ASP.NET MVC 5 and c# , any help would be really appreciated!
There's essentially 2 ways you can get that data back to the server:
You can put the data into a form element and post that form to an action that's set up to receive it. This will require you to put your username, password, etc into a series of html elements with name attributes set up to follow MVC's conventions (This page has some information on the conventions to use).
You can use jQuery's ajax features to send a raw javascript object containing your data to an MVC action (See this answer and it's linked post for details on how to accomplish this).
In either case, you probably shouldn't be sending a username & password to the server with every request, as you can use an authentication cookie to verify a user's identity once they're logged in to your application (there's plenty of resources online explaining how this works).
For option 2:
Javascript:
var myobject = {
username: "Joe",
password: "password",
points: [{ x: 111.1112, y: 22.2222 },{ x: 11.12, y: 21.11 }]
}
jQuery.ajax({
url: "/MyController/MyAction",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(myobject)
})
C#:
public class PointModel
{
public double x { get; set; }
public double y { get; set; }
}
public class MyModel
{
public string username { get; set; }
public string password { get; set; }
public IList<PointModel> points { get; set; }
}
public class MyController : Controller
{
[HttpPost]
public JsonResult MyAction(MyModel model) {
...
}
}
you can use below java script method to define JavaScript array
<script type="text/javascript">
var array = [];
array.push(10);
array.push(20);
</script>
you use this array to insert points in array and send this array using following Ajax call
var _data = {
'array ': array
};
$.Post(url ,_data, function(data){
})

Data Filter - View User Interface

I have an Asp.Net MVC web app that I need to provide a user interface in the view to apply data filters to display a subset of the data.
I like the design of what is used on fogbugz with a popup treeview that allows for the selection of data filters in a very concise manner: http://bugs.movabletype.org/help/topics/basics/Filters.html
My controller's action method has some nullable parameter's for all of the available filters:
public ActionResult EmployeeList(int? empId, int? month, int? year,
string tag1, string tag2 //and others....)
{
//...filter employee list on any existing parameters
return View(viewModel);
}
My intention was whenever a filter was applied by clicking on a link, entering text...that filter would be added to the parameter list and reload the page with the correct data to display.
Looking for some guidance or examples on how to create a filter toolbar or best practices for this type of problem. I haven't been able to find a jquery ui plugin or javascript library to do something similar to this so a little lost on where to start.
Thanks.
I did something similar to this by having a main page containing a number of dropdowns containing the parameter options, then a div that had the resultant set ViewUserControl loaded into it on both page load and on dropdown selection change. The controller for the data, in this case TaskList, just needs to return a normal ActionResult View(newTaskList(data)); Example below.
<script>
$(document).ready(function () {
loadDataSet();
});
function loadDataSet(){
var status = document.getElementById('ddlStatus');
var selectedStatus = status.options[status.selectedIndex].value;
if (status.selectedIndex == 0) selectedStatus = '';
$.post('<%= Url.Action("TaskList") %>', { status: selectedStatus },
function (data) {
$('#divTaskList').html(data);
});
}
</script>
<%= Html.DropDownList("ddlStatus", Model.StatusOptions, null, new { onchange = "javascript:loadDataSet();" })%>
<div id='divTaskList' />

Categories

Resources