I have a html form that submits to a C# ashx handler that i'm hoping will insert/update the database
I've written this in PHP and Coldfusion, but I cannot figure out how to do this in C#
HTML form
<form id="copyto">
<input type="hidden" name="operation" value="update" />
<label><input type="checkbox" name="children[]" checked="checked" value="001">
Andrew Regan</label>
<label><input type="checkbox" name="children[]" checked="checked" value="101">
Arthur Regan, III</label>
<input type="checkbox" name="children[]" checked="checked" value="968">
Tim Reagan
</form>
C# ASHX handler
foreach(string key in context.Request.Params["children"])
{
ListDictionary updateParams = new ListDictionary();
updateParams.Add("rowid", key);
string sSql = #"insert into temp select * from children where c.id = :rowid";
dbi.ExecuteNonQuerySql(sSql, updateParams);
}
Typically i would iterate over the $_POST['children'] in php , and execute the sql
How exactly does this translate?
EDIT
ok ive almost gotten this, however my iterator goes over ALL of the request collection variables, i want it to go over only a specific named variable, in this case "children"
i.e localhost/page?operation=update&children=9&children=8&children=17
foreach(string key in context.Request.QueryString)
{
ListDictionary updateParams = new ListDictionary();
updateParams.Add("row_id", context.Request.QueryString[key]);
string sSql = #"insert into dug select :row_id from dual";
dbi.ExecuteNonQuerySql(sSql, updateParams);
}
i want it to ignore everything but the specific var
If you are doing a post. I think something like this would work.
<input type="checkbox" name="children" value="108"/>
<input type="checkbox" name="children" value="109"/>
<input type="checkbox" name="children" value="110"/>
<input type="checkbox" name="children" value="111"/>
The browser will send all of the values comma seperated to the server when the form is submited
Then on your server side you can do this:
var selected = context.Request.Form["children"].Split(',');
Selected will be an array of strings for each value that was passed in by the browser. You can then loop over them and do whatever you need to.
Hope this helps some.
I was just working on this yesterday. I ended up using a hidden field that will hold the multiple checked checkbox id's. So, if that route works for you, you could create a checkboxlist editor template or control. This could have a script such as:
(tempId will hold the common "name" attribute's value for your checkbox/checkboxlist, and we have the "somehiddenfield" hidden field to hold the selected values)
<script>
$(function () {
var arrTmp = [];
//Update array on selection change
$('input[name="#String.Format("{0}[]", tempId)"]').change(function () {
arrTmp = [];
$('input:checked[name="#String.Format("{0}[]", tempId)"]').each(function () { arrTmp.push($(this).val()); });
$('input[id="somehiddenfield"]').val(arrTmp.join(','));
});
});
</script>
Then, on postback on the server-side the form collection will simply have the hidden field we wrote the checked values into. Split that in whatever way works for you (like comma separated in my example) and you're good to go. My server-side is implemented in MVC but for WebForms you can pull the elements from the Request.Form dictionary (Request.Form["somehiddenfield"].ToString()) or even Request.Params as you are using.
Right after i put out the bounty of course -_-
foreach (string k in context.Request.QueryString)
{
if (k.StartsWith("children")){
foreach (string v in context.Request.QueryString.GetValues(k)){
ListDictionary updateParamss = new ListDictionary();
updateParamss.Add("row_id", v);
string Sql = #"insert into dug select :row_id from dual";
dbi.ExecuteNonQuerySql(Sql, updateParamss);
}
}
}
Related
I'm a beginner. I'm still studying. I have made this code, which works as intended.
However, for each time I go back to another page, it can not, of course, save it to a list.
It disappears directly after I'm gone from this page.
The server page looks like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult pizaCart(string pizaName, string pizaDesc, string pizaPrice)
{
List<pizaModel> cartList = new List<pizaModel>();
toCart.CartList = cartList;
pizaName = Request.Form["pizaName"];
pizaDesc = Request.Form["pizaDesc"];
pizaPrice = Request.Form["pizaPrice"];
cartList.Add(new pizaModel { name = pizaName, desc = pizaDesc, price = pizaPrice });
return View(toCart);
}
html page looks like this.
<form action="piza" method="post">
<input class="n" type="text" name="pizaName" id="pizaName" value="" /><br />
<input class="n" type="text" name="pizaDesc" id="pizaDesc" value="" /><br />
<input class="n" type="text" name="pizaPrice" id="pizaPrice" value="" /><br />
<button class="btn">add</button>
</form>
"I have tried to google it and look for it lots of places, but havent found any good enough answer"
-- hmm i probably need a loop somewhere?
As you can see, it's a very simple way to post data to list. Is it possible that I can keep adding to my list? (Maybe it has something to do with lifecycle). Thank you very much for your time.
When you call
new List<pizaModel>()
...you are creating a new list. A new list has zero elements.
Immediately after that you call
cartList.Add(new pizaModel { name = pizaName, desc = pizaDesc, price = pizaPrice });
...which adds the current item to the list, which results in a list with one item.
There is no notion in this code of adding to an existing list, and it will never contain more than one item.
You will need to figure out some way of keeping the list from action to action. For example, you could persist the list in the browser and then post the whole list as JSON. Or you could store the list in a session variable or database table on the server side.
You may use sessions as below
Session["myPizza"] = cartList ;
Then cast it from the end of your Action result as below
var SelectedList = (List<pizaModel>)Session["myPizza"];
I`m using MvcGrid.Net
Here is my cshtml page
<div class="well">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="Opprtunity ID" data-mvcgrid-type="filter" data-mvcgrid-option="opprtunityid" />
</div>
<div class="form-group">
<input class="form-control" placeholder="Cluster" data-mvcgrid-type="filter" data-mvcgrid-option="Cluster" />
</div>
<button type="button" class="btn btn-default" data-mvcgrid-apply-filter="click">Apply</button>
</div>
</div>
I have two simple search button. When I can try to bind them to the MVC grid confing file i can't see the value in the QueryOptions.
Here is my grid-options:
.WithRetrieveDataMethod((context) =>
{
var options = context.QueryOptions;
int totalRecords;
var repo = DependencyResolver.Current.GetService<General>();
string sortColumn = options.GetSortColumnData<string>();
var items = repo.GetData(out totalRecords,
options.GetFilterString("opprtunityid"),
options.GetFilterString("Cluster"),
//active,
options.GetLimitOffset(),
options.GetLimitRowcount(),
sortColumn, options.SortDirection == SortDirection.Dsc);
return new QueryResult<SourcedPartner>()
{
Items = items,
TotalRecords = totalRecords
}
options.GetFilterString("opprtunityid") here i have a null value.
Can someone explain me why?
When using MVCGrid.Net, you have to make sure that you set up the table definition in MVCGridConfig.cs .
Key elements to filtering are:
1) When declaring the column, you must make sure that you add the following code to the column definition -
.AddColumns(cols => {
cols.Add("opportunityid").WithVisibility(false)
.WithFiltering(true) // MUST have filtering enabled on column definion, otherwise it will not appear in QueryOptions
.WithValueExpression(i => i.OpportunityID);
cols.Add("Cluster").WithHeaderText("Cluster")
.WithFiltering(true)
.WithVisibility(false)
.WithAllowChangeVisibility(true)
.WithValueExpression(i => i.Cluster);
2) You must make sure to include filtering as part of your MVCGridBuilder construction -
MVCGridDefinitionTable.Add("Filtered", new MVCGridBuilder<SourcedPartner>()
.AddColumns(....)
.WithSorting(true, "MySortedColumnName")
.WithFiltering(true) // This lets the GridContext know that something will populate QueryOptions.Filters section
.WithRetrieveDataMethod((context) =>
{
var options = context.QueryOptions;
string opID = options.GetFilterString("opprtunityid");
string cluster = options.GetFilterString("Cluster");
.......
});
When you debug your code, the Filters portion of QueryOptions will be populated with your values from the input boxes. If there is no value, you will have a zero length string that you must check for.
The column needs to have filtering enabled. The builder must have filtering enabled. The column name must match the data-mvcgrid-option name.
When all of these things are set up, you should see the value from your inputs in the Filter section of the QueryOptions.
Know this is late, hope this helps.
Look in the URL to see what variable/s are being sent and set accordingly in options.GetFilterString(******).
Worked for me.
I have a view that uses the next Model
#model Merak.Models.Product.Options.NumberOfObjectsProductOptionModel
And 2 radiobuttons
#Html.RadioButton(Constants.HtmlControlValues.OptionNumberObjectSelect, #Model.OptionOnePrice, true) <br/>
#Html.RadioButton(Constants.HtmlControlValues.OptionNumberObjectSelect, #Model.OptionTwoPrice)
Inside constants.HtmlControlValues.OptionNumberObjectSelect is a string with "groupname" inside.
I would think that the Html control would generate something like:
<input id="groupname" name="groupname" type="radio" value="50,00">
But instead it generates something like:
<input id="NumberOfObjectsProductOptionModel_groupname" name="NumberOfObjectsProductOptionModel.groupname" type="radio" value="50,00">
Any idea why this behaviour is happening and what I can do to get the short name/id version?
You can assign the constants.HtmlControlValues.OptionNumberObjectSelect to a variable a then get the value:
#model Merak.Models.Product.Options.NumberOfObjectsProductOptionModel
#{
string myControl = constants.HtmlControlValues.OptionNumberObjectSelect
}
And then use it in your control:
#Html.RadioButton(#myControl, #Model.OptionOnePrice, true)
Could you use #Html.RadioButtonFor(model => Model.OptionOnePrice) and see if that works better. That way it's bound to your model.
I need to display results based on user selection from a drop down menu. The menu itself is dynamically populated with "jobquery".
I wrote the following code:
#{
var db = Database.Open("database");
String jobquery = "select description from match_jobs";
IEnumerable<dynamic> data = null;
var grid = new WebGrid(data, canPage: false);
if(IsPost)
{
var description = Request["job"];
String sql = "select top 30 * from match_#0_output";
data = db.Query(sql, description);
}
}
Then in html, I have
<div id="dynamic">
Select Job
<form name = "search" method="post">
<select name="job">
<option value="" selected disabled>Select Job</option>
#foreach (var row in db.Query(jobquery))
{
<option value="#Request["job"]">#row.description</option>
}
</select>
<input type="submit" value="#Request["job"]"/>
</form>
</div>
The drop down menu worked fine. However, I am unable to call
#grid.GetHtml(); -> A data source must be bound before this operation can be performed.
I tried
</tr>
#foreach (var row in data)
{<tr>
<td>#row.columnname</td>
</tr>
}
Didn't work either. -> NullOperation Exception
I Googled all week and conducted loads of failed experiments. At my wit's end now; expert help will be greatly appreciated. Thank you...
In the first section of your code, you declare a variable for your data, but you don't query the database at all. I'm not completely clear what you are trying to do but if you want to populate the grid with data, you should query the database:
var db = Database.Open("database");
var jobquery = "select description from match_jobs";
var data = db.Query(jobquery);
var grid = new WebGrid(data, canPage: false);
Then in your "html", you don't need to query the database again - you can re-use the variable that already holds the data:
<div id="dynamic">
Select Job
<form name = "search" method="post">
<select name="job">
<option value="" selected disabled>Select Job</option>
#foreach (var row in data)
{
<option value="#Request["job"]">#row.description</option>
}
</select>
<input type="submit" value="#Request["job"]"/>
</form>
</div>
The section of code in the IsPost condition makes no sense at all. You query the database and then call Response.Redirect - telling the browser to request a different page. All values in the current page - including the data you have just retrieved are discarded when you do this.
I have a checkbox group in a view.
name = "group";
I want to iterate throug this group of checkboxes but I need to find a way to fetch them together;
All selected checkboxes are being posted with their values.
Would I be able to do something like this (one straight statement):
string[] name = Request.QueryString('group');
foreach(string value in name) {
}
The checkboxes are not returned on your query string but rather POSTed to your controller.
Only the selected checkbox values will be returned. To retrieve the entire list of possible checkbox values, you will need to reassemble those from your source.
#foreach (var item in Model.tags)
{
<label>
<input type="checkbox" name="Tag" value="#item.TagID"
#if (item.Selected) { <text>checked="checked"</text> }
/>
#item.Name
</label>
}
[HttpPost]
public RedirectToRouteResult MyAction(IEnumerable<int> Tag)
{
}
andleer's solution will work (with a minor adjustment that I made to his answer and that needs to be approved). However, there is a better way to handle list of checkboxes.
Please see CheckBoxList(For) extension