Get single values from ViewBag SelectList - asp.net-mvc

This question should be rather simple.
I have the following code:
ViewBag.SenderID = new SelectList(db.Senders, "SenderID", "SenderContactName", survey.SenderID);
//Attempts
string _SenderContactName = ViewBag.SenderID.ToString();
string _senderContactName = survey.SenderID.ToString();
Results:
_SenderContactname = System.Web.MVC.SelectList
_senderContactName = "1"
What I want the result to be is the SenderContactName from the VewBag, in the form of a string.
I Believe my second attempt is closer to the working code. But I canĀ“t seem to figure out how to fix it on my own.

In your case you should do:
string _senderContactName = db.Senders
.FirstOrDefault(x => x.SenderID == survey.SenderID)
.SenderContactName;

Related

java swagger 3 annotations #ExampleObject from jsonfile

I'm documention one of my api with multiple examples like this:
#Operation(summary = "Create new")
#PostMapping("")
public ResponseEntity<Object> createOne(
#Parameter(description = "MyDto")
#io.swagger.v3.oas.annotations.parameters.RequestBody(
content = #Content(examples = {
#ExampleObject(name = "one", value = EXAMPLE_ONE),
#ExampleObject(name = "two", value = EXAMPLE_TWO),
#ExampleObject(name = "three", value = EXAMPLE_THREE)}
))
#RequestBody MyDTO body
) {
...
}
This works fine, though EXAMPLE_ONE is a string value. This is pretty unclear as you can see from the example below
private static final String EXAMPLE_ONE = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";
I looking for a better way to provide the example. A json file would be nice, but I couldn't find anything about that.
You can use externalValue instead of value. See here
Use java text-block instead of normal quoted string
e.g. putting triple double (""")
see https://www.baeldung.com/java-text-blocks

Getting values from Bind. One key returns "0"

I want to make a few strings out of the Bind values. Easy enough except that one of them is messing with me. _surveyID = "0"
SurveyController:
public ActionResult Create([Bind(Include = "SurveyID,SurveyName,SenderID,ConsultantID,ResponderID,Question1,Question2,Question3,Question4,Question5,SurveyTime")] Survey survey)
{
if (ModelState.IsValid)
{
string _surveyID = survey.SurveyID.ToString();
string _surveyName = survey.SurveyName;
string _surveyTime = survey.SurveyTime.ToString();
//ANOTHER ATTEMPT, SAME RESULT
//string _surveyID = db.Surveys
//.FirstOrDefault(x => x.SurveyID == survey.SurveyID)
//.SurveyID;
}
SurveyID to database = 1002
SurveyID to my _surveyID = "0"
Notice that _surveyName and _surveyTime are both working fine.
The survey Bind values: http://i.imgur.com/khEDUns.png
Why is my SurveyID beeing set to 0 when I try to pull out the value?
EDIT: Is the ID value created when beeing put into database? Is my code too soon in the flow of code?
EDIT2: This is a bump1

Only first parameter value is getting while calling controller method using Url.action.

I am calling a controller method using Url.action like,
location.href = '#Url.Action("Display", "Customer", new { username = "abc",name = "abcdef",country = "India",email = "abc#hmail.com",phone = "9456974545"})';
My controller method is,
public void Display(string username, string name, string country, string email, string phone)
{ }
In this method, I can get only the value of first parameter (username). Its not getting other parameter values that is passed. All other values are null.
Please suggest me, whats wrong?
By default every content (which is not IHtmlString) emitted using a # block is automatically HTML encoded by Razor.
So, #Url.Action() is also get encoded and you are getting plain text. And & is encoded as &
If you dont want to Encode then you should use #Html.Raw(#Url.Action("","")).
The answer for you question is :
location.href = '#Html.Raw(#Url.Action("Display", "Customer", new { username = "abc",name = "abcdef",country = "India",email = "abc#hmail.com",phone = "9456974545"}))';
Hope this helps
There is a problem with '&' being encoded to the '& amp;'
model binder doesnt recognise this value. You need to prevent this encoding by rendering link with Html.Raw function.
Use '#Html.Raw(Url.Action......)'

Dart: How to bind to variables annotated with int via Web UI?

What is the best practice in Dart when dealing with classes as data records?
To Elaborate: When writing an app, it is likely that a class for a table row will be created. As in
class Item { int itemid, String itemName, double score }
Item item = new Item();
This allows compile time catching of any typos etc. in Dart. (Unlike using a class that relies on NoSuchMethod.)
It will also need a corresponding string structure to bind to the HTML such as
<input id="itemname" type="text" bind-value="itemEdit.itemName">
So the Dart would be:
class ItemEdit { String itemId, String itemName, String score }
ItemEdit itemEdit = new ItemEdit();
Next we need a way to get from one to the other, so we add a method to Item
fromStrings(ItemEdit ie) {
itemid = ie.itemId == null ? null : int.parse(ie.itemId);
itemName = ie.ItemName;
score = ie.score == null ? null : double.parse(ie.score);
}
And the other way around:
toStrings(ItemEdit ie) {
ie.itemid = itemId == null ? '' : ie.itemId.toString();
ie. itemName = itemName == null ? '' : itemname; // Web_ui objects to nulls
ie.score = score == null ? null : score.toStringAsFixed(2);
}
Also, we get jason data from a database, so we need to add another method to Item:
fromJson(final String j) {
Map v = JSON.parse(j);
itemid = v['itemid'];
itemname = v['itemname'];
score = v['score'];
}
And we need to be able to revert to default values:
setDefaults() { itemId = 0; itemName = "New item"; score = 0; }
This verbosity gets me feeling like I am writing COBOL again!
There is something fundamental missing here - either in my understanding, or in the Dart/WebUI libraries.
What I would like to write is something like
class Item extends DataRecord {
int itemid = 0,
String itemName = 'New item',
double score = 0.0;
}
Then, without further coding, to be able to write code such as
item.toStrings();
...
item.fromStrings();
...
item.fromJson(json);
...
item.setDefaults(); // results in {0,'New item',0.0}
And to be able to write in the HTML:
value="{{item.strings.score}}"
If this was possible, it would be quicker, simpler, clearer, and less error prone than the code I am writing at the moment.
(Full disclosure, this answer is written with the assumption that at least one bug will be fixed. See below)
Three suggestions that might help.
Use named constructors to parse and create objects.
Take advantage of toJson() when encoding to JSON.
Use bind-value-as-number from Web UI
1) Named constructors
import 'dart:json' as json;
class Item {
int itemid;
String itemName;
double score;
Item.fromJson(String json) {
Map data = json.parse(json);
itemid = data['itemid'];
itemName = data['itemName'];
score = data['score'];
}
}
2) Encoding to JSON
The dart:json library has a stringify function to turn an object into a JSON string. If the algorithm encounters an object that is not a string, null, number, boolean, or collection of those, it will call toJson() on that object and expect something that is JSON-encodable.
class Item {
int itemid;
String itemName;
double score;
Map toJson() {
return {'itemid':itemid, 'itemName':itemName, 'score':score};
}
}
3) Now, having said that, sounds like you want to easily bind to HTML fields and get primitive values back, not just strings. Try this:
<input type="number" min="1" bind-value-as-number="myInt" />
(Note, there seems to be a bug with this functionality. See https://github.com/dart-lang/web-ui/issues/317)
(from https://groups.google.com/a/dartlang.org/forum/#!topic/web-ui/8JEAA5OxJOc)
Just found a way to perhaps help a little in the this situation:
class obj {
int gapX;
String get gapXStr => gapX.toString();
set gapXStr(String s) => gapX = int.Parse(s);
...
Now, from the HTML you can use, for example
bind-value="gapXStr"
and in code you can use
x += ob.gapX;

How to parse multiple nodes of html using HtmlAgilityPack?

I'd appreciate if someone could help! I'm trying to parse the following page of Groupon website http://www.groupon.com/browse/chicago?category=activities-and-nightlife
var webGet = new HtmlWeb();
var deal1 = webGet.Load("http://www.groupon.com/browse/chicago?category=activities-and-nightlife");
I want to get the whole block of each Deal(i.e. offer for discount)
HtmlNodeCollection content_block = deal1.DocumentNode.SelectNodes("//div[#class = 'deal-list-tile grid_5_third']");
Then out of each block i want to get title, company name, location and price.
foreach(HtmlNode node in content_block)
{
string title2 = node.SelectSingleNode("//div[#class = 'deal-title js-permalink']").InnerText;
string country2 = node.SelectSingleNode("//p[#class = 'merchant-name']").InnerText;
string location2 = node.SelectSingleNode("//p[#class = 'location']").InnerText;
string price2 = node.SelectSingleNode("//div[#class = 'price']/span").InnerText;
}
Here i get confused, i need to write all the information about deals into
DbSet<Deal> Deals , but even if i try to display the content as ViewBag.Message = title + country + location + price; i get System.NullReferenceException: Object reference not set to an instance of an object in the line with content_block.
What am i doing wrong =(
Thanks in advance!
The problem appears to be that the selectnodes returns nothing or null when no nodes are found instead of an empty collection. so this means you should probably wrap if (content_block != null) { around your code block above.

Resources