How to fill document header from jqgrid data - c#

ASP .NET MVC2 page contains order header data (order number, customer, order data etc):
<form id='_form' class='form-fields' action='' onsubmit='SaveDocument();return false;'>
<input id='Number' name='Number' />
<select id='PaymentTerm' name='PaymentTerm'>
<option value=''></option><option value='0'>Cash</option>
<option value='10'>10 days</option>
</select>
</form>
and order rows presented in jqgrid.
I'm looking for a way to fill order headcer data from json date from controller like
like jqgrid fills data.
To minimize request maybe it is best to return header data in jqgrid data request.
For this additional parameter documentId is passed to controller.
GetData returns document header as name value pairs in document object.
How to assign those values to form elements in browser in jqgrid loadcomplete or other place ?
public JsonResult GetData(int page, int rows, string filters,
int documentId )
{
var query = ...;
var totalRecords = query.Count();
var documentHeader = new FormCollection();
// In production code those values are read from database:
documentHeader.Add("Number", 123); // form contains input type='text' name='Number' element
documentHeader.Add("PaymentTerm", "10"); // form contains select name='PaymentTerm' element
...
return Json(new {
total = page+1,
page=page,
document = documentHeader,
rows = (from item in query
select {
id = item.Id.ToString(),
cell = new[] {
item.ProductCode,
item.ProductName,
item.Quantity,
item.Price
}
}).ToList()
},
JsonRequestBehavior.AllowGet);
}

If I understand correct your question you can use beforeProcessing or loadComplete callbacks to fill the form data based on the response from the server. The first data parameter of both callbacks (beforeProcessing or loadComplete) will contains all the data returned from the server. So you have access to document property of data and it has the same format as on the server.
I am not sure why you use document of the type FormCollection. It seems to me the most native to use anonymous type of data:
return Json(new {
total = page + 1,
page = page,
document = new {
number = 123,
paymentTerm = 10
},
rows = (...)
},
JsonRequestBehavior.AllowGet);
but the exact type of document is probably not so important.
Inside of beforeProcessing or loadComplete you can just use the corresponding properties of data.document in the same format. For example
beforeProcessing: function (data) {
var hearderData = data.document;
if (hearderData) {
if (hearderData.number) {
$("#Number").val(hearderData.number);
}
if (hearderData.paymentTerm) {
$("#PaymentTerm").val(hearderData.paymentTerm);
}
}
}

Related

How to get and set multiple checkbox values based on serverside data using bootstrap multiselect plugin

Here I have dropdownlist which contains multiple values. and user can select any no of values by clicking the checkbox infront of the value as shown below.
Following is my c# code.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"), new { id = "det" , multiple= "multiple"})
$(document).ready(function() {
$('#det').multiselect();
});
When user click save button I want to get the user selected list. I am using following code to get the values.
$("#det").val()
But the above value is empty. How to get the existing selected value?
And also I want to show the values as selected based on server side values.
I am creating model and set model property with hardcoded values as below.
model.Detail = "Cheese, Tomatoes";
But these values are not getting selected in dropdownlist as well.
Used plugin here - link
Any help?
Thanks.
You need to add multiple= "multiple" in the attributes for multiselect to work.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"),
new { id = "det", multiple= "multiple" });
to set the values:
<script>
var selectedValues = #model.Detail;
var dataarray = selectedValues.split(",");
// Set the value
$("#det").val(dataarray);
$("#det").multiselect("refresh");
</script>
First of all, use #Html.ListBoxFor that works best with Multiselect js.
In order to get the values for selected options, I have created the following client side code which returns list of value in form of String arrays
function GetDropDownVal() {
var selectidList = [];
var selectedItem = $("#ListQueCatId").val();
// .multiselect("getChecked") can also be used.
if (selectedItem != null) {
for (var i = 0; i < selectedItem.length; i++) {
selectidList.push(selectedItem[i]);
}
}
return selectidList;
}
This is how I have implemented the code
View Side Code
#Html.ListBoxFor(m => m.ListQueCatId, (SelectList)ViewBag.AllQueCat as MultiSelectList, new { #class = "form-control listQueCatIdDdl" })
Javascript Code
$(".listQueCatIdDdl").multiselect({ noneSelectedText: "--Select Category(s)--" });
Also, make sure to bind a model property of Type List in my case, ListQueCatId is List< Guid>, hence while you post the form, you will get the selected values in your model.
Also, I don't think there is need to add multiple attribute as the plugin is meant for selecting multiple values.

DropDownList not setting selected value

I'm running asp.net 4 mvc and I've created a DropDownList of dates that defaults to the first entry in the list. When I select an entry, I invoke a controller function and do some processing. However, when my page does the PostBack, instead of displaying the list item I selected, it displays the original default list item again.
How do I get my page to display the last item I selected from the list? I've spent two full days searching this site and the Internet for a solution but nothing I try seems to work. Any assistance would be greatly appreciated.
My Html View
#Html.DropDownList("selectList", Model.ReverseMonthsLists(),
new { #onchange = "CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
window.location.href = "/dashboard/Report_Performance?id=" + val;
}
</script>
My ViewModel
public SelectList MonthList { get; set; }
public IEnumerable<SelectListItem> ReverseMonthsLists()
{
var selectListItems = GetDates()
.Select(_ => _.ToString("MMM yyyy"))
.Select((dateString, index) => new SelectListItem { Selected = index == 0, Text = dateString, Value = dateString })
.ToList();
return selectListItems;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = new DateTime(2017, 6, 1).Date;
var currentDate = DateTime.Now.Date;
int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
var dates = new List<DateTime>(numberOfMonthsToShow);
currentDate = currentDate.AddMonths(-1);
for (int i = 0; i < numberOfMonthsToShow; i++)
{
dates.Add(currentDate);
currentDate = currentDate.AddMonths(-1);
}
return dates;
}
My Controller
[RequireLogin]
public ActionResult Report_Performance(string id)
{
DateTime newDate = DateTime.Now.Date.AddMonths(-1);
if (id != null)
newDate = DateTime.Parse(id);
var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, newDate);
return this.View(aVar);
}
You can change your code as follows:
Let's say your model class that is being returned by GetStats method in the Report_Performance action is MyStats which contains a string property named SelectedDateString (you need to add this property to your view model class).
Updated view markup:
#model MyStats
#Html.DropDownList("SelectedDateString", Model.ReverseMonthsLists(),
new { #onchange = "CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
window.location.href = "/dashboard/Report_Performance?id=" + val;
}
</script>
Updated controller:
[RequireLogin]
public ActionResult Report_Performance(string id)
{
DateTime newDate = DateTime.Now.Date.AddMonths(-1);
if (id != null)
newDate = DateTime.Parse(id);
var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, newDate);
//This will make sure that the model returns the correct value of the property as a string.
aVar.SelectedDateString = id;
return this.View(aVar);
}
A Html.DropDownList() works by getting data from a string property in the model which is of the same name as the name of the DropDownList itself.
In your case, you need to set the DropDownList value using javascript or jquery as it's not connected to a model property.
Let me give you an example:
A drop down list in MVC can be created by using either
#Html.DropDownListFor(m => m.PreferredContactMethod, Model.PreferredContactMethods, "")
or
#Html.DropDownList("PreferredContactMethod", Model.PreferredContactMethods, "")
In both cases, PreferredContactMethod is a string property in my model that is connected to the view - which is done by specifying #model PreferredContactModel at the top of the view.
In your case, your list name is selectList and if the specified model is connected to the view and if there's a property in the model that gets the selected date, then you need to change the name of your drop down list to it.
I hope it makes sense, if there's any issue, please comment back. I want to help with this.
The problem is here:
window.location.href = "/dashboard/Report_Performance?id=" + val;
This essential tells the browser to navigate to a new page, which is an HttpGet operation. Thus, there is no correlation between your current settings and those of a new page.
It's as if you had just gone up to the address bar and hit enter. It issues a new page with all new defaults.
There are many ways you can address this problem. The easiest would be to have some javascript that looks at the URL and extracts the id query parameter, then selects the item in the dropdown box that corresponds with the id.
Another option is to set the dropdownlist's selected value based on the ID in your controller.
In controller:
ViewBag.SelectedItem = id;
In View:
#Html.DropDownList("SelectedItem", Model.ReverseMonthsLists(), ...)

Ajax jquery autocomplete in ASP.NET MVC 5 C#

I know there's a lot of these kind of post but I wasn't able to find any that suited me. I don't have knowledge of ajax and jquery (in fact I've just started with MVC and ASP.NET) so I need your help in this little thing.
There must be almost everywhere this kind of silly thing, I want to write a city name in a combobox, dropdownlist (or whatever) and using a method that I've already created which returns a list of locations (city, country and state names) that match the entered city. I want it to be dinamyc that's why I thought AJAX would solve this (but any other solution is accepted)
I found this jQuery autocomplete but I don't understand where to implement it. I want the combobox to match the bootstrap theme. Could someone tell me if this is an appropiate solution and if so where do I put the ajax content and else? (by where I mean, is it in the view, or controller or where?)
Or you could give mi a hint here is the method I've created for getting the elements from the database:
public List<LocationsViewModel> GetHeadquarter(string query)
{
var context = new HeadquarterContext();
//var city = context.Cities.Where(p => p.Name == query).Single();
//var province = context.Provinces.Where(p => p.ProvinceID == city.Province).ToList();
//foreach(Province prov in province) {
//}
var hq =
from c in context.Cities
join p in context.Provinces on c.Province equals p.ProvinceID
join co in context.Countries on p.Country equals co.CountryID
where c.Name == query
select new { country = co.Name, province = p.Name, city = c.Name };
List<LocationsViewModel> listLocation = new List<LocationsViewModel>();
foreach (var hqe in hq)
{
LocationsViewModel loc = new LocationsViewModel();
loc.City = hqe.city;
loc.Country = hqe.country;
loc.Province = hqe.province;
listLocation.Add(loc);
}
return listLocation;
}
Lets see if we can get it to work.
View:
This is added in your view, #Url.Action(Action, Controller) is the Action that is the source for the autocomplete function.
<input type="search" class="form-control ui-autocomplete"
data-autocomplete="#Url.Action("Autocomplete", "Home")" />
Controller (Home):
As you can see the Action Autocomplete was used to search for a product. I have an instance of my database entity called '_db' and have select a table called 'product_data' (can also use a Stored Procedure). I'm using LINQ to query the datasource and store it in the variable 'model', so it's querying where the 'term' StartsWith what is typed in the textbox, it takes the top 10 and for each one it add label and product. [{"label":value}]
public ActionResult Autocomplete(string term)
{
try
{
var model = _db.product_data // your data here
.Where(p => p.product.StartsWith(term))
.Take(10)
.Select(p => new
{
// jQuery UI needs the label property to function
label = p.product.Trim()
});
// Json returns [{"label":value}]
return Json(model, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Settings.ReportException(ex);
return Json("{'ex':'Exception'}");
}
}
JavaScript:
This code is when you select a value from the list that is displayed from your search. The 'window.location.href' redirects to a different controller once a value from the autocomplete has been selected.
// submits form upon selecting a value
var submitAutocompleteForm = function (event, ui) {
var $input = $(this); // the HTML element (Textbox)
// selected value
$input.val(ui.item.label); // ui.item.label = the label value (product)
window.location.href = "/Product/Details?id=" + ui.item.label;
};
The next function sets up the autocomplete API. You declare your options, the above is optional and it comes under select, the source is required and it points to the data-attribute on the HTML element.
var createAutocomplete = function () {
var $input = $(this); // the HTML element (Textbox)
var options = {
// selecting the source by finding elements with the 'data-' attribute
source: $input.attr("data-autocomplete"), // Required
select: submitAutocompleteForm // Optional
};
// apply options
$input.autocomplete(options);
};
// targets input elements with the 'data-' attributes and each time the input changes
// it calls the 'createAutocomplete' function
$("input[data-autocomplete]").each(createAutocomplete);
You'll have to reference the jQueryUI file for autocomplete to work.

How to use grid in VS2010 MVC3 to add and edit data?

I'm using Microsoft VS 2010 C#, MVC3.
I have Calsserooms and Students with many to many relation ship, so I add an intermediat table called Classroom_Students.
When adding students to a classroom, I use a combo box in my view filled with all students names, I choose one by one in every submit
#using (Html.BeginForm("AddStudentToClassroom", "Calssrooms", FormMethod.Post))
{
#Html.LabelFor(c=>c.Students, "Choose a Student")
<select name = "StudentID">
#foreach (var it in Model.Students)
{
<option value="#it.ID">#it.StudentName </option>
}
</select>
<input type="submit" value= "Add" />
}
My question is:
How can I use gride, instead of this combo, to select many students, select all or deselect all to add???
I'll appreciate any help.
This is the code in my controller.
For page first call, I fill combobox as following:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddStudentToClassroom(int id) //id of calssroom
{
using (ExaminationEntities en = new ExaminationEntities())
{
ClassroomDetails ClsromView = new ClassroomDetails (); // these are for
ClsromView.Classroom = en.Classroom.Single(c => c.ID == id);// loading calssroom information and to
ClsromView.Students = en.Students.ToList(); // fill students list for the combobox
return View(ClsromView);
}
}
When submiting the form, view, and click the add button, it calls the following overloaded add function for saving data:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddStudentToClassroom(AddStudToCals ClasStud) //ClasStud is the submited data from the view
{
using (ExaminationEntities en = new ExaminationEntities())
{
ClassroomDetails ClsromView = new ClassroomDetails(); // these are for
ClsromView.Calssroom = en.Calssroom.Single(c => c.ID == ClasStud.ClassroomID); // loading calssroom information and to
ClsromView.Students = en.Student.ToList(); // fill students list for the combobox
using (ExaminationEntities exn = new ExaminationEntities())
{
Calssroom_Student To_DB_ClasStud = new Calssroom_Student (); //To_DB_ClasStud object to get the submited values and to save it in the DB
To_DB_ClasStud.CalssroomID = ClasStud.CalssroomID;
To_DB_ClasStud.StudentID = ClasStud.StdentID;
en.AddToClassroom_Student(To_DB_ClasStud);
en.SaveChanges();
}
return View(ClsromView);
}
}
Well, the option that requires the least changes to your markup is to add the multiple property to your select. Then, change the action method to accept a params int[] ids, iterate through them, and you should be good-to-go. At worst, you might have to change your parameter to a string and do a Split() on ,, but I don't recall that being how the model binder supports multi-selects.
If this doesn't seem to fit your needs, there is an article on the ASP.NET website that explains using a MultiSelectList to bind to the ListBox helper, here:
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

how to get the value of a kendoui dropdown list selected value in a listview

am having Some kendoui listviews which consists of kendoui dropdown lists and i want to get those dropdown list selected values. To do this am trying,
$("#cnty1").val();
and here is my dropdownlist,i.e., list of countries coming from Database table,
<input select STYLE="width:90px;height:auto" id ="cnty1" data-bind="value:cnty1"
name="cnty1" data-type="string" data-text-field="cnty"
data-value-field="cntyid" data-source="sourcedata1" class="k-d"
data-role="dropdownlist" />
<span data-for="cnty1" class="k-invalid-msg"></span>
here cnty1 is the id of the dropdown list, but am not getting the value instead am getting "id" of the slected value but not the selected value.
And also if the value is not selected am getting the first value id by using $("#cnty1").val();
So, please suggest me a solution so that,
1) I should get only the Selected value and
2) Value of the dropdown list Only if the user selects a value from the list, but don't get the value of the list without selecting.
try this one.
<select STYLE="width:90px;height:auto" id ="cnty1" data-bind="value:cnty1"
data-text-field="cnty" data-value-field="cntyid" data-source="sourcedata1" data-role="dropdownlist" data-change="cntySelect" data-option-label="Select"></select>
function cntySelect(e) {
var dropDownVal = $("#cnty1").val();
alert(dropDownVal);
}
Use the following jquery to get selected value/text:
For value:
$("#cnty1 option:selected").val();
For text use:
$("#cnty1 option:selected").text();
Although this code is being used for FK JSON objects in KendoUI grid, the idea is similar. You have to bind the object on dropdown value selection. The dropdown essentially contains options that are your value ID's, not the objects themselves. Therefore, you have to iterate through the data source to find which object has been selected and then do the replacement in data model.
/**
* KendoDropDownEditor Class
* */
var KendoDropDownEditor = Class({
initialize: function (schema, gridId, readUrl) {
var readUrl = readUrl || base + schema.entityName + "/read";
this.dataSource = DataSourceGenerator.crudDS(schema, gridId, readUrl);
this.dataTextField = schema.model.dropDownTextField;
this.dataValueField = schema.model.id;
},
/**
*
* */
do:function (container, options) {
var self = this;
var a = $('<input data-text-field="' + self.dataTextField + '" data-value-field="' + self.dataValueField + '" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind:false,
dataSource:self.dataSource,
close:function (e) {
$.each(self.dataSource.data(), function(key, value) {
if (value[self.dataValueField] == e.sender.value()) {
options.model[options.field] = value;
return false;
}
});
}
});
}
});
Also look at Knockout-Kendo, it could make your life easier.

Categories