HTML Helper Class - asp.net-mvc-3

I am using this code and is working fine.
#Html.TextBox("myname", "somevalue", new { #class = "css-class", #onclick = "alert('demo');" id="mynewID"})
But there is another overload for this:
HTMLHelper.Textbox(string name, object value, IDictionary<string,object> htmlattribute)
I am using like:
#Html.TextBox("myname", "", new Dictionary<string, object> { { "id", "f","class","ds" } })
but getting compilation error...please help

The error you are getting is due to the incorrect syntax used in the dictionary initializer. You can see that easily if you add this code to a class and try to compile:
var dict = new Dictionary<string, object> { { "id", "f", "class", "ds" } };
You will see that you get the error:
No overload for method 'Add' takes 4 arguments
You need to pass each object to the dictionary as a key value pair, as in this code (notice each key-value pair surrounded by curly brackets):
var dict = new Dictionary<string, object> { { "id", "f" }, { "class", "ds" } };
So you can use that overload of the HtmlHelper as in the following example:
#Html.TextBox("myname", "", new Dictionary<string, object> { { "id", "f"}, {"class", "ds" } })

Related

Load section of config file into dictionary in net 5.0

I have to work on an application in net 5.0 not developed by me, that I don't know.
I would like to add a section in the config file and load it into a dictionary.
this is the section in config file:
{
"MyApp": {
"ServiceExceptions": [
{ "Key1": "Value1" },
{ "Key2": "Value2" }
]
}
}
this code load the configuration:
public static IConfiguration GetConfiguration(string name)
{
IConfiguration oConfiguration = null;
string basePath = Path.GetDirectoryName(typeof(SharedHelper).Assembly.Location);
string configPath = Path.Combine(basePath, "Config");
string fileConfig = string.Format("{0}.{1}.json", name, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
oConfiguration = new ConfigurationBuilder()
.SetBasePath(configPath)
.AddJsonFile(fileConfig, optional: false, reloadOnChange: true)
.Build();
return oConfiguration;
}
this is the code to load to bind the dictionary, but myExceptions is null:
_Configuration = GetConfiguration("BD.Authentication.DWA");
Dictionary<string, string> myExceptions = null;
_Configuration.GetSection("MyApp:ServiceExceptions").Bind(myExceptions);
Debug.WriteLine(myExceptions.Count); // throws exception null reference
somewhere are loaded the data, but i dont know how to pull out
Just move the config file in:
{
"MyApp": {
"ServiceExceptions":
{ "Key1": "Value1" },
{ "Key2": "Value2" }
}
}
and retrive the values:
var serviceTypeExceptions = _Configuration.GetSection("MyApp:ServiceExceptions").Get<Dictionary<string, string>>();

Not able to get TermVector results properly in SolrNet

I'm not able to get TermVector results properly thru SolrNet. I tried with the following code.
QueryOptions options = new QueryOptions()
{
OrderBy = new[] { new SortOrder("markupId", Order.ASC) },
TermVector = new TermVectorParameters
{
Fields = new[] { "text" },
Options = TermVectorParameterOptions.All
}
};
var results = SolrMarkupCore.Query(query, options);
foreach (var docVectorResult in results.TermVectorResults)
{
foreach (var vectorResult in docVectorResult.TermVector)
System.Diagnostics.Debug.Print(vectorResult.ToString());
}
In the above code, results.TermVectorResults in the outer foreach gives the proper count whereas docVectorResult.TermVector in the inner foreach is empty.
I've copied the generated solr query of the above code and issued against solr admin and I'm properly getting the termVectors values. The actual query I issued is below
http://localhost:8983/solr/select/?sort=markupId+asc&tv.tf=true&start=0&q=markupId:%2823%29&tv.offsets=true&tv=true&tv.positions=true&tv.fl=text&version=2.2&rows=50
First you should check HTTP query to sure termvector feature is set property.
If it's not OK, change your indexing based on:
The Term Vector Component
If it is OK,You can use "ExtraParams" by changing the handler to termvector handler. Try this:
public SolrQueryExecuter<Product> instance { get; private set; }
public ICollection<TermVectorDocumentResult> resultDoc(string q)
{
string SERVER="http://localhost:7080/solr/core";//change this
var container = ServiceLocator.Current as SolrNet.Utils.Container;
instance = new SolrQueryExecuter<Product>(
container.GetInstance<ISolrAbstractResponseParser<Product>>(),
new SolrConnection(SERVER),
container.GetInstance<ISolrQuerySerializer>(),
container.GetInstance<ISolrFacetQuerySerializer>(),
container.GetInstance<ISolrMoreLikeThisHandlerQueryResultsParser<Product>>());
instance.DefaultHandler = "/tvrh";
SolrQueryResults<Product> results =
instance.Execute(new SolrQuery(q),
new QueryOptions
{
Fields = new[] { "*" },
Start = 0,
Rows = 10,
ExtraParams = new Dictionary<string, string> {
{ "tv.tf", "false" },
{ "tv.df", "false" },
{ "tv.positions", "true" },
{ "tv", "true" },
{ "tv.offsets", "false" },
{ "tv.payloads", "true" },
{ "tv.fl", "message" },// change the field name here
}
}
);
return results.TermVectorResults;
}

Use a Linq statement to perform outer join

Starting with the collection below, what Linq statement do I need to return a results set that satisfies the test?
private List<dynamic> _results;
[SetUp]
public void SetUp()
{
_results = new List<dynamic>
{
new {Id = 1, Names = new[] {"n1"}, Tags = new[] {"abc", "def"}},
new {Id = 2, Names = new[] {"n2", "n3"}, Tags = new[] {"ghi"}},
new {Id = 3, Names = new[] {"n1", "n3"}, Tags = new[] {"def", "xyz"}},
new {Id = 4, Names = new[] {"n4"}, Tags = new string[] {}}
};
}
private ILookup<string, string> GetOuterJoinedCollection(IEnumerable<dynamic> results)
{
// ???
}
[Test]
public void Test()
{
ILookup<string, string> list = GetOuterJoinedCollection(_results);
Assert.That(list.Count, Is.EqualTo(4));
Assert.That(list["n1"], Is.EquivalentTo(new [] { "abc", "def", "def", "xyz" }));
Assert.That(list["n2"], Is.EquivalentTo(new [] { "ghi" }));
Assert.That(list["n3"], Is.EquivalentTo(new [] { "ghi", "def", "xyz" }));
Assert.That(list["n4"], Is.EquivalentTo(new string[] { }));
}
Note: this is a follow up from a previous question: Convert Lambda into Linq Statement with nested for loop

Additional parameters for TextBoxFor() in ASP.net MVC3

I was using a textbox to do the following:
<input style="width:50px;" type="text" id="blah" value="#model.value1" #if(model.id!=1){ <text>disabled</text>}/>
This basically shows a textbox which is disabled under specific circumstances.
I decided to replace this with a more "mvc-friendly" way.
#Html.TextBoxFor(m => model.value1, new { id = "blah" })
But not sure how to add in the disabled attribute (Dynamically) I can get it to do it statically easilly by adding a disabled=truevalue into the new{}.
I did try using this:
#if (<condition>) { var disable = true; }
#Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = disable })
But this also didn't work. Am i taking the right approach here?
#{
var attributes = new Dictionary<string, object>
{
{ "id", "blah" }
};
if (<condition>)
{
attributes["disabled"] = "disabled";
}
}
#Html.TextBoxFor(m => model.value1, attributes)
Obviously that's ugly as hell and you should never even be thinking of polluting your view like that. I would simply write a custom reusable HTML helper:
public static class HtmlExtensions
{
public static IHtmlString MyTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> ex,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(ex, attributes);
}
}
that you could use in the view as simply as:
#Html.MyTextBoxFor(m => model.value1, new { id = "blah" }, <condition>)
You have a scope issue with the above disable doesn't exist outside the scope of the if statement,
my recommendation is this:
#Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) })
EDIT:
You can use
#Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) ? "disabled" : "" })
If you want to insert the word disabled rather than a bool, from memory this is kinda a browser specific setting some are happy with "true" others with "disabled"

ModelsState always invalid when using Html.DropDownListFor

This is how I create my dropdown
#Html.DropDownListFor(model => model.NewPageModel.AvailablePageModels, new SelectList(Model.NewPageModel.AvailablePageModels, "Text", "Value"))
and this is how my AvailablePageModels looks like
public IEnumerable<SelectListItem> AvailablePageModels
{
get
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(PageModelAttribute), true).Length > 0)
{
yield return new SelectListItem { Text = type.Name, Value = type.Name };
}
}
}
}
}
and when I post my form to the following action my modelstate is always invalid and the error occur on the AvailablePageModel value? Maybe I cannot use the NewPageModel as a parameter this way?
public ActionResult Create([Bind(Prefix = "NewPageModel")] NewPageModel newPageModel, FormCollection collection)
{
if(ModelState.IsValid) {
// always invalid
}
}
You need 2 fields, one for the available options in the drop down list and one for storing the selected value
Html.DropDownListFor(m => m.NewPageModel.SelectedModel,
new SelectList(Model.NewPageModel.AvailablePageModels, "Text", "Value"))

Resources