I am populating an input field value where sometimes the value exists and sometimes it doesn't I need to check if the value is empty and show nothing if it is not. My current code is using .IsNullOrEmpty :
<input id="lead-entry" class="form-textbox" type="text" size="5" name="q15_2013Collections[0][]"
value="#(queryinputvalue.FirstOrDefault(r => r.field_name.Equals("q15_2013Collections[0][]")).field_data.IsNullOrEmpty
? ""
: queryinputvalue.FirstOrDefault(r => r.field_name.Equals("q15_2013Collections[0][]")).field_data) " />
Which gives me the error:
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
Thanks
Edit: this is the code I finally used:
Helpers.cshtml
#helper checkEmpty(IEnumerable<dynamic> queryinputvalue, string field_id) {
var reqValue = queryinputvalue.FirstOrDefault(r => r.field_name.Equals(field_id));
var return_value = "";
if(reqValue != null){
return_value = reqValue.field_data;
} else {
return_value = "";
}
#return_value
}
On Page
#{
IEnumerable<dynamic> queryinputvalue = db.Query("SELECT * FROM document_data WHERE doc_id = #0", doc_id);
}
<input type="text" class=" form-textbox" id="input_4" name="q4_arborLoan" size="20" value="#Helpers.checkEmpty(queryinputvalue,"q4_arborLoan")" />
Why are you doing this in View? You have to check for these conditions in the controller while populating your ViewModelas below:
public class ViewModel
{
public string QueryValue {get ; set;}
}
And in your controller method you would simply populate this model and return it in View page.
public ActionResult MyMethod()
{
ViewModel model = new ViewModel();
//Get someValue from anywhere.
string reqValue = someValue.FirstOrDefault(r => r.field_name.Equals("q15_2013Collections[0][]"));
string queryValue = string.Empty();
if(queryValues != null)
{
queryValue = string.IsNullOrEmpty(reqValue .field_data)
? ""
: reqValue .field_data;
}
model.QueryValue = queryValue ;
return View(model);
}
So, your View will simply become
#model ViewModel
<input id="lead-entry" class="form-textbox" type="text" size="5" name="q15_2013Collections[0][]" value="#Model.QueryValue" />
Related
Form returns url format: localhost2343/index?Colors=red&Colors=blue&Colors=pink
asp-route return url format: localhost2343/index?Colors=red,blue,pink
If I use form submit button than everything seems good. But If i click on sort hyperlink than it will pass URL Colors=System.String%5B%5D
How can I pass value of Colors inside asp-route?
<form asp-page="./index" method="get">
<select asp-for="Colors" asp-items="#Model.Colors_SELECT" class="MultiSelect" multiple>
<option value="">All</option>
</select>
...
</form>
<Table>
...
<a asp-page="./Index" method="get"
asp-route-SortOrder="#Model.Colors_Sort"
asp-route-SearchString="#Model.SearchString"
asp-route-Colors="#Model.Colors">
#Html.DisplayNameFor(model =>
model.MyList[0].Colors)
</a>
...
</table>
[BindProperty(SupportsGet = true)]
public string[]? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }
public async Task OnGetAsync()
{
// Form - URL Format
// get values from URL & set inside selectlist
var result = Request.Query["Colors"];
var i = 0;
foreach (string? item in result) {
Colors[i] = item;
i++;
}
}
Update - I tried this but on sort link, it removes Sort variable & it picks only 1 Colors (not multi)
<a asp-page="./Index" method="get"
asp-route-SortOrder="#Model.Colors_Sort"
asp-all-route-data="#Model.routeData">
[BindProperty(SupportsGet = true)]
public Dictionary<string, string> routeData { get; set; }
....
var routeData = new Dictionary<string, string>();
routeData.Add("SortOrder", CurrentSort);
routeData.Add("SearchString", SearchString);
for (int i = 0; i < result.Count; i++)
{
var myParam = result[i];
routeData.Add($"Colors{i}", myParam.ToString());
}
This may help:
To get the selected values from a select element in a Razor page, you can use the Request.Form["selectName"] collection.
For example, consider the following select element:
#page "{Colors}"
<form method="post">
<select multiple name="colors">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="pink">Pink</option>
</select>
<button type="submit" asp-page-handler="GetColors">Submit</button>
</form>
To get the selected values in the form submission handler and modify the query string in the URL and include the selected values (red, blue, pink), you can try the following code:
public IActionResult OnGet(string? Colors)
{
if (string.IsNullOrWhiteSpace(Colors))
{
// do something
return Page();
}
if (!string.IsNullOrWhiteSpace(Colors))
{
// Do something
return Page();
}
return Page();
}
public IActionResult OnPostGetColors()
{
IDictionary<string, string> params = new Dictionary<string, string>();
var selectedColors = string.Join(",", Request.Form["colors"]);
params.Add("Colors", selectedColors);
string query = "";
foreach (var p in params)
query += $"{p.Key}={p.Value}";
var url = $"{HttpContext.Request.Path}?{query}";
return Redirect(url); // url : https://localhost:7272/index?Colors=red,blue,pink
}
This code will help you submit the selected values through the URL as a query string, and then will redirect the user to a new URL with the selected values added to the query string as multiple values for the colors parameter.
var dictionary = [];
dictionary.push({
key:"Res01" ,
value: "Loss of internet connection at location"
});
when adding this dictionary object to an input field
$('#hdnNotesDict').val('');
$('#hdnNotesDict').val(dictionary);
i am not getting the dictionary value in that input field.
getting result as: [object,object]
Thanks in advance and any suggestion will be appreciated
Let's say you have this form in your view:
<form method="post">
<input id="kvps" name="kvps" />
<input id="submit" type="submit" value="Submit" />
</form>
and you put some values like that:
(function () {
$('#submit').mousedown(function () {
let input = $('#kvps');
let dict = [];
for (var i = 0; i < 10; i++) {
dict.push({ key: `Res${i}`, val: `Val${i}` });
}
input.val(JSON.stringify(dict));
});
})();
in this case you convert the array in a string and you should take it as string into your controller
BUT - you cannot convert it to dictionary immediately, first you should map it to array of model with the same property names then you can call ToDictionary over it.
Array example:
[HttpPost]
public IActionResult JInput(string kvps)
{
var arr = JsonSerializer.Deserialize<object[]>(kvps);
return this.View();
}
If you need it as Dictionary<string, string> you schould use in your jquery object instead:
(function () {
$('#submit').mousedown(function () {
let input = $('#kvps');
let dict = {};
for (var i = 0; i < 10; i++) {
// watch out for the keys here to not overwrite the values
dict[`Res${i}`] = `Val${i}`;
}
input.val(JSON.stringify(dict));
});
})();
And in your controller like that:
[HttpPost]
public IActionResult JInput(string kvps)
{
var arr = JsonSerializer.Deserialize<Dictionary<string, string>>(kvps);
return this.View();
}
i keep getting errors when trying to post an <input type="number"> from my view to my controller using FormCollection. the database type for expenseBackup is a decimal(8,2). I keep getting "Cannot impliticity convert string to decimal?". Then when i try expenseBackup = Int32.Parse(formValues["expenseBackup"]), i get "Input string was not in correct format". i don't want to have to convert anything in the controller i don't understand why it won't just pass as a decimal through the FormCollection.
Controller
[HttpPost]
public ActionResult Create(FormCollection formValues)
{
var data = new usr_ebillingClientDatabase()
{
client = formValues["client"], //is a string from form
expenseBackup = formValues["expenseBackup"] //is a decimal from form
};
dataContext.table1.InsertOnSubmit(data);
try
{
dataContext.SubmitChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
return RedirectToAction("Index");
}
}
View
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(model => model.expenseBackup, new { htmlAttributes = new { #class = "form-control" , , #type="number", #step=".01" } })
</div>
</div>
when you're reading the field from formValues["expenseBackup"] it's being read as a string. Convert it to a decimal using Convert.ToDecimal().
expenseBackup = Convert.ToDecimal(formValues["expenseBackup"] ?? 0m);
FormCollection is a key-value pair collection (NameValueCollection) which returns values as string based from provided key, which is also a string. If you're in doubt which number format applied by numeric input during submit, use combination of decimal.TryParse() and if-condition with string.IsNullOrEmpty() to check null/empty string value:
decimal expense;
if (!string.IsNullOrEmpty(formValues["expenseBackup"])
&& decimal.TryParse(formValues["expenseBackup"], out expense))
{
var data = new usr_ebillingClientDatabase()
{
client = formValues["client"],
expenseBackup = expense
};
// insert to database
}
else
{
// unable to parse numeric value, do something else
}
If you're sure that numeric representation passed in FormCollection uses certain decimal separator other than default, use NumberFormatInfo when parsing with decimal.Parse()/decimal.TryParse():
var numberFormat = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "," };
var data = new usr_ebillingClientDatabase()
{
client = formValues["client"],
expenseBackup = decimal.Parse(formValues["expenseBackup"], numberFormat);
};
However, I recommend using strongly-typed viewmodel over FormCollection because you're using EditorFor, and it will pass property values directly to controller when viewmodel name is included as action parameter.
I'm displaying dropdown list using html. then when a user select a item from the list that item's id or name or something should pass to my next view's controller.
this is my code...
***** this is my first controller *****
public ActionResult searchView()
{
XElement cruProductRoot = XElement.Load(Server.MapPath("~/XmlFiles/Cruisedata/cruiseprodutstwo.xml"));
var rootElement = cruProductRoot.Elements("CruiseProduct");//this is the root element
//for the location field
var getLocations = rootElement
.Select(l => l.Element("Location").Value)
.Distinct();
var getType = rootElement
.Select(t => t.Element("Types").Element("Type").Value)
.Distinct();
// Test productsTestone = new Test();
List<Test> productsLocation = new List<Test>();
List<Test> productsType = new List<Test>();
foreach (var iteml in getLocations)
{
productsLocation.Add(new Test
{
cruiseLocation = iteml.ToString()
});
};
foreach(var itemt in getType)
{
productsType.Add(new Test
{
cruiseType = itemt.ToString(),
});
}
ViewBag.Lc = productsLocation;
ViewBag.Tp = productsType;
return View();
}
*** and this is the view for the controller ****
#using (#Html.BeginForm("Test", "searchView", FormMethod.Post))
{
<div class="form-group" style="background-color:#808080; padding:30px;">
<div class="col-md-6" style="margin:10px;">
<label for="location">Destination </label>
<select id="location">
<option>Any</option>
#foreach (Test item in #ViewBag.Lc)
{
<option value=#item.cruiseLocation>#item.cruiseLocation</option>
}
</select>
</div>
</div>
******** this is my second controller ******
public ActionResult resultView(string value)
{
XElement sCruise = XElement.Load(Server.MapPath("~/XmlFiles/Cruisedata/cruiseprodutstwo.xml"));
var rootEle = sCruise.Elements("CruiseProduct")
.Where(s => s.Element("Location").Value == value);
foreach(var it in rootEle)
{
}
return View();
}
**** when user select an item from the list, and click submit then the selected item should send to the second view's controller. how can I do that.
if we use only links like this.
#Html.ActionLink(#itme.cruiseLocation,"resultView", new {name =#item.cruiseLocatin})
how to do for option also.I tried <option>#Html.ActionLink</option> also. help me with this
In first controller set
TempData["optionid"]=selectedid
And in second controller you can access that id from var a=TempData["optionid"]
I am using a method that generate my questions and answers i mean every questions appear in view and the answers of this question are put to the DDL as you can see here :
public string GenerateHtmlCode()
{
string result = string.Empty;
List<ExecutiveOfficer> executiveOfficers = executiveOfficerRepository.GetAll().ToList();
List<Indicator> indicators = indicatorRepository.GetAll().ToList();
foreach (ExecutiveOfficer executiveOfficer in executiveOfficers)
{
result += "<div style='width:100%;float:right;'><span>" + executiveOfficer.ExecutiveOfficerText +
"</span><span style='float:left'>" +
GenerateAnswer(indicatorRepository.FindBy(i => i.ExecutiveOfficerId == executiveOfficer.Id
).ToList(), executiveOfficer.Id) + "</span></div>";
}
return result;
}
In my create method in controller i pass the string to viewbag as you can see here :
[HttpGet]
public ActionResult Create(int preliminaryId)
{
ViewBag.preliminaryId = preliminaryId;
ViewBag.pageGenarator = objScoreRepository.GenerateHtmlCode();
// List<ExecutiveOfficer> executiveOfficer = objScoreRepository.GetAll().ToList();
//ViewBag.executiveOfficerName = new SelectList(executiveOfficer, "Id", "ExecutiveOfficerText");
return View("Create");
}
My html code :
</span><span style='float:left'><select id='1' name ='1'><option value='value1'>displaytext</option><option value='value2'>displaytext2</option></select></span>
As you can see here i have 1 DDL that has 2 values i need to get the value that is selected by the user i use the form collection to get the name of DDl as you can see here :
[HttpPost]
//[Authorize(Roles = "Expert")]
public ActionResult Create(FormCollection formCollection)
{
//objScoreRepository.Add(Score);
//objScoreRepository.Save();
foreach (var VARIABLE in formCollection.AllKeys)
{
}
return RedirectToAction("Create", "Score");
}
The formcollection just returns one record and the record is 1 the name of DDL .But i need to get the value of DDL.How can i do that?
My view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_LayoutIdeaOtherPage.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.Raw(ViewBag.pageGenarator)
<div class="buttonPossion">
<input type="submit" Class="buttonSave" />
</div>
}
best regards .
You can use
foreach(string item in form.AllKeys)
{
var value = Request[item];
}