How on earth do you get the return value from an MVC2 checkbox - asp.net-mvc-2

I have a checkbox on one of my forms. And unfortunately, I cant't seem to figure out how to get the value out of the thing on the server side (my controlller). How in sam hill do you do that? It seems like you have to do a check for when the form ellement if not false?
How do you do this?
Adding some addition information
if ((formCollection["popID"] != null) && (formCollection["StartDate"] != null) && (formCollection["EndDate"] != null) && (formCollection["sendAnyway"] != null))
{
string popId = formCollection["popID"];
if (formCollection["StartDate"] != "")
{
startDate = DateTime.Parse(formCollection["StartDate"]);
}
if (formCollection["EndDate"] != "")
{
endDate = DateTime.Parse(formCollection["EndDate"]);
}
Boolean sendAnyway = Boolean.Parse(formCollection["sendAnyway"]);
if (client.ProcessGetABBYPopulation(popId, startDate, endDate, sendAnyway) == false)
{
return PutToQError("Error placing message on Queue");
}
else
{
//return Success("You successfully placed a message on the Queue");
return RedirectToAction("Home", "Home");
}
}
Here is my view (where I have a checkbox)
<%:Html.Label("Reprocess patients already sent during this timeframe?") %>
<%:Html.CheckBox("sendAnyway") %>
Update 2
Checking my return value it returns, "true,false"
what kind of sense does that make?

If you're not using a strongly typed view model, you're probably doing something like this:
<% Html.CheckBox("someName") %>
In which case, you can access it when you POST it to your server like so:
public ActionResult SomeMethod(string someName) // Bound via name on the parameter
{
string value = Request.Form["someName"]; // Or pulled from the Form collection
// someValue / value = "1" or whatever your checkbox value was, IF SELECTED.
// If unselected, it's NULL.
}
If you're using a strongly typed view model, it's available the same way:
<% Html.CheckBoxFor(x => x.IsSet) %>
And then accessed like:
public ActionResult SomeMethod(MySampleViewModel vm)
{
vm.IsSet; // true if selected, false if not
string request = Request.Form["IsSet"];
// request = value of your checkbox, NULL otherwise.
}

Related

telerik mvc Create CompositeFilterDescriptor and append it to existing datasource request filter

I am having some issues creating a CompositeFilterDescriptor from scratch.
The scenario: We have date filters on the grid, but are showing date time fields.
When Someone filters to a specific date, we show all records for that day.
when someone filters greater than that day, we edit the filterDescriptor for that filter and add one day to it.
when someone filters to less than or equal to that day, we edit the filterdescriptor for that filter and add one day to it.
Here is the problem: when someone selects "not equal to", the solution would be to create a compositeFilterDescriptor containing two filters. One for less than that day, one for greater than that day.
I may ore may not be doing this part properly. I can not figure out how to add the new compositeFilterDescriptor to the existing dataSourceRequest.
Here is what I have:
static public DataSourceRequest FixDateFilters(DataSourceRequest request, string[] optionalFields = null)
{
if (request?.Filters != null)
{
List<string> matchingFields = new List<string> { "utc", "time" };
List<FilterDescriptor> newDescriptors = new List<FilterDescriptor>();
//if any fields specific to a page have been passed in, append them to the list.
if (optionalFields != null)
{
foreach (string field in optionalFields)
matchingFields.Append(field);
}
foreach (string matchingField in matchingFields)
{
List<FilterDescriptor> descriptors = new List<FilterDescriptor>();
FilterDescriptor descriptor1 = FindFirstFilterByMember(request.Filters, matchingField, true, null);
//there could be up to two filters on a matching field. Get the 2nd one if it exists.
FilterDescriptor descriptor2 = FindFirstFilterByMember(request.Filters, matchingField, true, descriptor1);
//turn the matches into a list for iterating
if (descriptor1 != null)
descriptors.Add(descriptor1);
if (descriptor2 != null)
descriptors.Add(descriptor2);
if (descriptors.Count != 0)
{
foreach (FilterDescriptor descriptor in descriptors)
{
DateTime? utcDate = (DateTime?)descriptor?.Value;
if (utcDate.HasValue)
{
utcDate = Core.DateHelper.ToUTC(utcDate.Value, HttpContext.Current); //make sure date ranges are one day ranges in local time
}
if (utcDate != null)
{
if (descriptor.Operator == FilterOperator.IsLessThanOrEqualTo)
{
utcDate = ((DateTime)utcDate).AddDays(1);
descriptor.Value = utcDate;
}
else if (descriptor.Operator == FilterOperator.IsGreaterThan)
{
utcDate = utcDate.Value.AddDays(1);
descriptor.Value = utcDate;
}
else if (descriptor.Operator == FilterOperator.IsEqualTo)
{
descriptor.Operator = FilterOperator.IsGreaterThanOrEqualTo;
newDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsLessThan, utcDate.Value.AddDays(1)));
}
else if (descriptor.Operator == FilterOperator.IsNotEqualTo)
{
CompositeFilterDescriptor cfd = new CompositeFilterDescriptor();
cfd.LogicalOperator = FilterCompositionLogicalOperator.Or;
cfd.FilterDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsLessThan, utcDate.Value;));
cfd.FilterDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsGreaterThan, utcDate.Value.AddDays(1)));
newDescriptors.Add( cfd);
}
}
}
}
}
//equals matches add a new descriptor so add them after the foreach is done so they don't affect the foreach.
foreach (FilterDescriptor newDescriptor in newDescriptors)
{
if (newDescriptor.Member != "") //a blank descriptor has a emptry string for member
{
request.Filters.Add(newDescriptor);
}
}
}
return request;
}
}
static public FilterDescriptor FindFirstFilterByMember(IEnumerable<IFilterDescriptor> filters, string findMember, bool partialMatch = false, FilterDescriptor previous = null)
{
FilterDescriptor ret = null;
foreach (var filter in filters)
{
var descriptor = filter as FilterDescriptor;
if (descriptor != null
&& (descriptor.Member == findMember || (partialMatch == true && descriptor.Member.ToLower().Contains(findMember.ToLower())))
&& (previous == null || previous != descriptor))
{
ret = descriptor;
break;
}
else if (filter is CompositeFilterDescriptor)
{
ret = FindFirstFilterByMember(((CompositeFilterDescriptor)filter).FilterDescriptors, findMember, partialMatch, previous);
if (ret != null)
break;
}
}
return ret;
}
The second function is a recursive one for getting the filters by string.
The problem section is the "isNotEqualTo" comparison. I don't know how to save the composite filter into the existing request. It gives me a casting error.
Ok it turns out all i needed to do was create a new list of CompositeFilterDescriptor type and append that when necessary. The .add function took both. Sigh.
foreach (CompositeFilterDescriptor newCompositeDescriptor in newCompositeDescriptors)
{
request.Filters.Add(newCompositeDescriptor);
}

Getting WorkbookPart from row

I am writing and extension for OpenXML like shown in the sample. I would like to avoid having to pass the WorkbookPart as parameter. Is there any way to get the WorkbookPart directly from the row?
public static string GetCellTextValue(this Row row, WorkbookPart workbookPart, string column)
{
var cells = row.Elements<Cell>();
var cell = cells.Where(p => p.CellReference == column + row.RowIndex.ToString()).FirstOrDefault();
if (cell.DataType != null)
{
if (cell.DataType == CellValues.SharedString)
{
int id = -1;
if (Int32.TryParse(cell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
return item.Text.Text;
}
else if (item.InnerText != null)
{
return item.InnerText;
}
else if (item.InnerXml != null)
{
return item.InnerXml;
}
}
}
}
return string.Empty;
}
Unfortunately, none of the strongly-typed classes of the Open XML SDK (e.g., Workbook, Worksheet, Row) have properties pointing back to the OpenXmlPart (e.g., WorkbookPart, WorksheetPart) in which they are contained or any other part related to their immediate container. Unless you amend your API in other ways, you will have to pass that WorkbookPart.

"the operation cannot be completed because the dbcontext has been disposed entity framework" error is no var userinfo line

Error happens on the var userinfo line... I'm new to ASP.NET MVC and I'm trying to create a sample project to learn ASP.NET MVC, but got stuck here. I searched other posts with similar errors, but the issue was with not saving .
public ActionResult Login(LoginViewModel c)
{
using (db = new DBEntities())
if (!ModelState.IsValid)
{
return View(c);
}
// error happens on this line of code
var userinfo = db.e_usr.Where(m => m.usr_ename == c.Email && m.usr_pswd == c.Password).FirstOrDefault();
if (userinfo != null)
{
Session["LoginID"] = userinfo.usr_ename;
Session["LoginUser"] = userinfo.usr_pswd;
return Redirect("Home/Index");
}
return null;
}
You're missing a code block (by specifying { .... }) after your using statement. Therefore, the db is valid for only the next statement - the check whether your ModelState is valid or not. After that, the db variable is gone.
Change your code to:
public ActionResult Login(LoginViewModel c)
{
using (db = new DBEntities())
{ // <<<==== add this leading curly brace!
if (!ModelState.IsValid)
{
return View(c);
}
// Simplify your LINQ here - define the condition directly
// in the ".FirstOrDefault()" method
var userinfo = db.e_usr.FirstOrDefault(m => m.usr_ename == c.Email && m.usr_pswd == c.Password);
if (userinfo != null)
{
Session["LoginID"] = userinfo.usr_ename;
Session["LoginUser"] = userinfo.usr_pswd;
return Redirect("Home/Index");
}
return null;
} /// <<<==== add these closing curly braces
}

Silverstripe 3.1.x getting values from Parent

I would like to get a generic function working for getting Data in Template of a Page and if the property is not set, getting it from the Parent or Parents Parent and so on. With generic I mean independent of Relations like db, HasOne, HasMany, ManyMany. Let's say I have this for ManyMany but would like to detect if it's a Object, HasManyList or ManyManyList or a value. Is anything like this built in or how would you go about?
function ManyManyUpUntilHit($ComponentName){
$Component = $this->getManyManyComponents($ComponentName);
if($Component && $Component->exists())
return $Component;
$Parent = $this->Parent();
if(is_object($Parent) && $Parent->ID != 0){
return $Parent->ManyManyUpUntilHit($ComponentName);
} else {
return null;
}
}
in template:
$ManyManyUpUntilHit(Teaser)
There is no in built method to do this in Silverstripe. You will need to write your own function to do this.
Here is an example to get a page's has_one, has_many or many_many resource by parameter, or go up the site tree until a resource is found, or we hit a root page:
function getComponentRecursive($componentName) {
// has_one
if ($this->has_one($componentName)) {
$component = $this->getComponent($componentName);
if (isset($component) && $component->ID)
{
return $component;
}
}
// has_many
if ($this->has_many($componentName)) {
$components = $this->getComponents($componentName);
if (isset($components) && $components->count())
{
return $components;
}
}
// many_many
if ($this->many_many($componentName)) {
$components = $this->getManyManyComponents($componentName);
if (isset($components) && $components->count())
{
return $components;
}
}
if ($this->ParentID != 0)
{
return $this->Parent()->getComponentRecursive($componentName);
}
return false;
}

Do not submit empty form fields in ExtJS

I have an extjs form with fields. The user isn't required to enter data into each field so I do not want to submit the fields with no data. I want it to post only fields that actually have data. Is this possible?
I recommend using form's beforeaction event. While handling this event you can check all fields. If all values are empty just return false;. The following example works in ExtJS4 and has to work in ExtJS3:
myform.on('beforeaction', function(form, action) {
if (action.type == 'submit') {
var doSubmit = false, vals = form.getValues();
for (var i in vals)
if (vals[i] !== '') {
doSubmit = true;
break;
}
return doSubmit;
}
});
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
Another options is to override component's getSubmitValue() method and return null if this field is empty, this way it won't be included into submit fields.
{
xtype: 'combo',
getSubmitValue: function(){
var value = this.getValue();
if(Ext.isEmpty(value)) {
return null;
}
return value;
}
}
Instead of using form's submit, directly call Ext.Ajax.request(...) with the url, method type (GET/POST) and params (and any other options as explained in the call documentation).
To generate params, iterate over the form fields and check for null value before adding to params.
This bug is present in ExtJS 4.0.7 too.
As Molecule Man pointed:
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
A possible solution to fix this bug is by overriding 2 functions, getValues in "Ext.form.Basic" (where the bug is) and createForm (to create our basic form) in "Ext.form.Panel" by extension in the following way:
Ext.define("My.form.Basic", {
alias: "form.mybasic",
extend: "Ext.form.Basic",
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {};
this.getFields().each(function(field) {
if (!dirtyOnly || field.isDirty()) {
var data = field[useDataValues ? "getModelData" : "getSubmitData"](includeEmptyText);
if (Ext.isObject(data)) {
var isArray = Ext.isArray;
Ext.iterate(data, function(name, val) {
if (includeEmptyText && val === "") {
val = field.emptyText || "";
}
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0))) {
if (name in values) {
var bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
}
else {
bucket.push(val);
}
}
else {
values[name] = val;
}
}
});
}
}
});
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
}
});
Ext.define("My.form.Panel", {
alias: "form.mypanel",
extend: "Ext.form.Panel",
createForm: function() {
return Ext.create("My.form.Basic", this, Ext.applyIf({listeners: {}}, this.initialConfig));
}
});
The code is copied from the ext source code. The only change is inside the iteration of each field: introduced the following wrapping "if":
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0)))
I am a bit late but, better later than never...