Passing property delegate into Blazor component giving 'does not take 1 argument' error - delegates

I am trying to pass a property as a delegate into a Blazor component. However, I get a Delegate 'Func<Pen, int, stirng>' does not take 1 argument error. And uncertain what the correct syntax should be.
This is the component:
#typeparam TItem
<div class="MarelAutoComplete">
<div class="MarelAutoCompleteList">
#foreach (var item in Data.Select(Property))
{
...
}
</div>
</div>
#code {
[Parameter]
public List<TItem> Data { get; set; }
[Parameter]
public Func<TItem, string> Property { get; set; }
}
Below is the calling Code:
<MyComponent TItem="Pen"
TValue="myVal"
Data="Pens"
Property="pen => pen.PenNumber" /> // Error On This Line.
#code {
List<Pen> Pens { get; set; }
}

The error you report is Delegate 'Func<Pen, int, string>' does not take 1 argument yet Property is defined as Func<TItem, string>.
Func<TItem, string> Property says I want a function that looks like this:
string MyMethod(TItem item)
Your anonymous function is pen => pen.PenNumber, with Property expecting pen.PenNumber as a string. Is it?
Here's a simplified working version of what you're doing:
TextBox.razor
#typeparam TItem
<h3>#Value</h3>
#foreach (var item in Data.Select(this.Property))
{
<div>#item</div>
}
#code {
[Parameter] public string Value { get; set; } = "Bonjour";
[Parameter] public Func<TItem, string> Property { get; set; }
[Parameter] public List<TItem> Data { get; set; }
}
Index.razor
#page "/"
#using Blazor.Starter.Data
<div>
<TextBox TItem="Model" Data="models" Property="item => item.Value"></TextBox>
</div>
#code {
public string GetProperty(Model model)
{
return model.Value;
}
public List<Model> models => new List<Model>()
{
new Model() { Value = "Fred"},
new Model() { Value = "Jon"},
new Model() { Value = "Bob"},
};
public class Model
{
public string Value { get; set; }
}
}

The issue was a simple syntax issue. When defining input functions this way, the input variables need to be enclosed in brackets.
It worked by changing this:
Property="pen => pen.PenNumber"
to this:
Property="(pen) => pen.PenNumber"

Related

LINQ result is not showing as expected

I'm trying to query for a particular column & to show the item list in view properly one after another. Here is my code:
Controller:
public ActionResult ShowImage()
{
using (var context = new ImageTrialDBEntities())
{
var pathlist = (from s in context.Images
select s.ImageLink).ToList();
var model = new ImageModel();
model.ImageList = pathlist;
return View(model);
}
}
Model:
public class ImageModel
{
public string Image { get; set; }
public IList<string> ImageList { get; set; }
}
View:
<div>
#foreach (var s in Model.ImageList)
{
#Html.DisplayFor(x=>x.ImageList)
<br />
}
</div>
The list is showing like this:
I would like to show one at a time with a break in between. Please help.
Replace
#Html.DisplayFor(x=>x.ImageList)
with
#Html.DisplayFor(x=>s)
You have 2 loops in the view code. Try just printing out the variable s.

Use knockout.js for 4 cascading dropdowns based on a hierarchy of objects

I am trying to get four cascading dropdowns using knockout.js:
Search Criteria
Sub Criteria
Value
State
I was able to get the first cascade going (but not the others due to databinding issues) by using code from the following link:
http://blogs.msdn.com/b/thebeebs/archive/2011/12/01/price-calculator.aspx
The data for these dropdowns is being returned to my razor viewpage as an IEnumrable of SearchCriterion from an MVC view using ViewBag.CriteriaData variable. The code for my classes is as follows:
public class SearchCriterion
{
public string Text { get; set; }
public string Value { get; set; }
public List<SubCriterion> SubCriteria { get; set; }
}
public class SubCriterion
{
public string SearchCriterionValue { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public List<ColumnValue> ColumnValues { get; set; }
}
public class ColumnValue
{
public string SearchCriterionValue { get; set; }
public string SubCriterionValue { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public IEnumerable<StateValue> StateValues { get; set; }
}
public class StateValue
{
public string SearchCriterionValue { get; set; }
public string SubCriterionValue { get; set; }
public string ColumnValue { get; set; }
public IEnumerable<int> InputStateIds { get; set; }
public IEnumerable<int> OutputStateIds { get; set; }
public int SelectedInputStateId { get; set; }
public int SelectedOutputStateId { get; set; }
public string Text { get; set; }
public string Value { get; set; }
}
The issues I am facing are in the following portions of the .cshtml code:
What do I specify in this template for the other two dropdowns. e.g. the third dropdown needs to be bound to ColumnValue.Value (ColumnValue is part of SubCriterion)
<script id='criteriaRowTemplate' type='text/html'>
<tr>
<td><select data-bind='options: criteriaData, optionsText: "Text", optionsCaption: "Search Criterion", value: SearchCriterion' /></td>
<td><select data-bind='visible: SearchCriterion, options: SearchCriterion() ? SearchCriterion().SubCriteria : null, optionsText: "Text", optionsCaption: "Sub Criterion", value: SubCriterion' /></td>
<td><select data-bind='visible: SubCriterion, options: SubCriterion() ? SubCriterion().ColumnValues : null, optionsText: "Text", optionsCaption: "Column Value", value: ColumnValue'/></td>
<td><select data-bind='visible: ColumnValue, options: ColumnValue() ? ColumnValue().StateValues : null, optionsText: "Text", optionsCaption: "State", value: StateValue'/></td>
<td><button data-bind='click: function() { viewModel.removeLine($data) }'>Remove</button></td>
</tr>
</script>
Is this correct?
var CriteriaLine = function() {
this.SearchCriterion = ko.observable();
this.SubCriterion = ko.observable();
this.ColumnValue = ko.observable();
this.StateValue = ko.observable();
// Whenever the Search Criteria changes, reset the Sub Criteria selection
this.SearchCriterion.subscribe(function() { this.SubCriterion(undefined); }.bind(this));
this.SubCriterion.subscribe(function() { this.ColumnValue(undefined); }.bind(this));
this.ColumnValue.subscribe(function() { this.StateValue(undefined); }.bind(this));
};
How do I map the complete C# object with the Javascript object? It works if we just have the first two dropdowns:
// Create a Javascript object object with the same property names as the C# object
var dataToSearch = $.map(this.lines(), function (line) { return line.StateValue() ? line.StateValue() : undefined; });
var SearchObject = new function () {
this.StateValues = dataToSearch;
};
// Convert the object to JSON
var searchCriteria = JSON.stringify(SearchObject);
Does anything need to change here for the binding?
// Apply the data from the server to the variable
var criteriaData = #Html.Raw(#Json.Encode(ViewBag.CriteriaData));
var viewModel = new Criteria();
ko.applyBindings(viewModel, document.getElementById("criteriaDiv"));
EDIT:
I am now able to populate the cascading dropdowns (updated code above). Now I have 4 columns, each column having one of the dropdowns. I also have 1...n number of rows being added dynamically by using Knockoutjs. So, the user can now select values from these dropdowns and add more rows of dropdowns if he wants. The only thing remaining is to return the values that the user selects for the dropdowns to the controller(point 3 above). I am not sure how I can do that. Any help would be appreciated.
EDIT 2:
Added working code for Item # 3 and modified the ColumnValue and StateValue classes.
I'm not sure I fully understand your question, but I'm going to take a whack at it anyway :). I think you're looking for a way to "validate" if it is in fact time to allow the next drop down to be active?
If so, you could approach it from a standpoint of Computed Observables. Basically, you would bind each of your dropdowns to a computed value which is derived from the previous dependencies.
Let me write fiddle and I'll show you :)
OK, give this a shot...sorry for the delay...http://jsfiddle.net/farina/ZNBcM/3/
I update the answer, Hope, it will help new Comers.
Methods for Binding Hierarchical Dropdowns using Knockout JS in MVC
Here you can find the good example .

Razor view engine and model in html helpers

I'm trying to create form from such model:
class NewContractorModel
{
//...
public PhotoModel photos { get; set; }
//...
}
class PhotoModel
{
public List<Photo> f { get; set; }
}
From controller I do some manipulation (actually I removed some photos from the collection) on the model object and put them into the view page using this:
return new View("SomeView", model);
I've tried to create inputs (lets say hidden inputs) for each Photo.
for (int i = 0; i < Model.photos.f.Count; ++i)
{
#Html.HiddenFor(m => m.photos.f[i].Uri)
#Html.HiddenFor(m => m.photos.f[i].ThumbnailUri)
#Html.HiddenFor(m => m.photos.f[i].SmallThumbnailUri)
#Html.TextBoxFor(m => m.photos.f[i].Description, new { placeholder = "Dodaj opis" })
}
But as I noticed that this doesnt work because it dismiss all of model modifications (it still stores all Photos in List despite the fact that I've removed them in Controler method).
Then I tried this code:
for (int i = 0; i < Model.photos.f.Count; ++i)
{
Photo photo = Model.photos.f[i];
<input id="photos_f_#{#i}__Uri" name="photos.f[#{#i}].Uri" type="hidden" value="#photo.Uri"/>
<input id="photos_f_#{#i}__ThumbnailUri" name="photos.f[#{#i}].ThumbnailUri" type="hidden" value="#photo.ThumbnailUri"/>
<input id="photos_f_#{#i}__SmallThumbnailUri" name="photos.f[#{#i}].SmallThumbnailUri" type="hidden" value="#photo.SmallThumbnailUri"/>
<input id="photos_f_#{#i}__Description" name="photos.f[#{#i}].Description" placeholder="Dodaj opis" type="text" value="#photo.Description"/>
}
...and this time IT WORKS!
Can anyone explain me what is the difference between those two parts of code?
I've tried to swich this code more than ten times and it always work the same so it's not my fault. ;)
I think that there is a bug in HtmlHelper methods but is there any walk-around ? I'd like to use helpers methods instead of raw html.
EDIT:
This is simplified controller class.
public class MyController
{
private NewContractorModel _model = null;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_model = SerializationUtility.Deserialize(Request.Form["Data"]) as NewContractorModel;
if (_model == null)
_model = TempData["Data"] as NewContractorModel;
if (_model == null)
_model = new NewContractorModel() as NewContractorModel;
TryUpdateModel(_model);
}
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (filterContext.Result is RedirectToRouteResult)
TempData["Data"] = _model;
}
private bool CheckModel(object model)
{
Type type = model.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo p in properties)
{
object[] attr = p.GetCustomAttributes(true);
foreach (object a in attr)
{
if (a is ValidationAttribute)
{
object value = p.GetValue(model, null);
if (!((ValidationAttribute)a).IsValid(value))
return false;
}
}
}
return true;
}
protected ActionResult SelectPage(string delPhoto)
{
if (!CheckModel(_model))
{
// Do some action
}
//.....
foreach (ZAY.Database.Photo p in _model.photos.f)
{
if (p.Uri == Request["delPhoto"])
{
_model.photos.f.Remove(p);
break;
}
}
//.....
return View("SomeView", _model);
}
}
I noticed that inside lambdas the model looks just like after TryUpdateModel call (before modifications). If I don't use lambdas the model is modified... :/
And also my Photo class (generated from EntityFramework - so there is nothing interesting) and also simplified:
public class Photo : EntityObject
{
[Required]
public string Uri { get; set; }
[Required]
public string ThumbnailUri { get; set; }
[Required]
public string SmallThumbnailUri { get; set; }
public string Description { get; set; }
}
I'm sorry that I'm writing only such small snippets but the whole code is more complicated - there is only the most interesting part of it.
This is the answer to my problem:
http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
I wonder why it is not mentioned in documentation... :/
From your description, I don't really understand what's going wrong in your first sample. But you certainly have a problem with the scope of the loop variable i.
Since the expression m => m.photos.f[i] involves closures, it will be evaluated at a later time, at a time when the for loop has already finished. The expression captures the variable i (and not the value of the variable i). When it is eventually evaluated, it finds the value Model.photos.f.Count in the variable i. So all hidden fields and textboxes will use the same invalid value of i.
Your second code sample avoids this problem by using a local variable within the for loop.

CheckBoxList does not update the model

I defined a Person entity:
public partial class Person
{
public string persID { get; set; }
public string last_name { get; set; }
public string driving_licence { get; set; }
}
where the driving licence is as follows:
public class DrivingLicence
{
public string drivingLicenceValue { get; set; }
public string drivingLicenceText { get; set; }
public DrivingLicence(string paValue, string paText)
{
drivingLicenceValue = paValue;
drivingLicenceText = paText;
}
}
having a repository where is defined this function:
public List<DrivingLicence> GetAll()
{
try
{
var drivingLicenceList = new List<DrivingLicence>();
DrivingLicence oneDrivingLicence = new DrivingLicence("A", "A");
drivingLicenceList.Add(oneDrivingLicence );
oneDrivingLicence = new DrivingLicence("B", "B");
drivingLicenceList.Add(oneDrivingLicence );
oneDrivingLicence = new DrivingLicence("C", "C");
drivingLicenceList.Add(oneDrivingLicence );
oneDrivingLicence = new DrivingLicence("D", "D");
drivingLicenceList.Add(oneDrivingLicence );
return drivingLicenceList;
}
catch (Exception)
{
throw new Exception("An error occured. Failed to Get the list.");
}
}
Now: I want the driving licences displayed as a CheckBoxList and on submit I want the person to get assigned the checked driving licence categories, e.g.: the "A" and "C" categories are selected, the resulting person.driving_licence must be "AC".
The problem is that this does not happen, the person is created but the driving_licence property is empty. I payed attention that the check boxes name be identical to that of the corresponding property (Person.driving_licence).
Is that an error in the present code? Or should I modify the Person entity?
Thank you for your advice.
Here is the view model:
public class PersonFormViewModel
{
// Properties
public Person person { get; set; }
public SelectList DrivingLicenceList { get; set; }
public string ActionToPerform { get; set; }
public PersonFormViewModel() { }
// Constructor
public PersonFormViewModel(Person pPerson, SelectList pDrivingLicenceList)
{
person= pPerson;
DrivingLicenceList = pDrivingLicenceList;
if (String.IsNullOrEmpty(person.persID))
{
ActionToPerform = "Create";
}
else
{
ActionToPerform = "Edit";
}
}
}
The controller:
//
// GET: /Person/Create
[Authorize]
public ActionResult Create()
{
Person person = new Person();
SelectList drvLicenceList = new SelectList(drvLicenceRepository.GetAll(), "drivingLicenceValue", "drivingLicenceText");
return View("Create", new PersonFormViewModel(person, drvLicenceList));
}
//
// POST: /Person/Create
[HttpPost, Authorize]
public ActionResult Create(PersonFormViewModel model)
{
Person person = model.person;
SelectList drvLicenceList = new SelectList(drvLicenceRepository.GetAll(), "drivingLicenceValue", "drivingLicenceText");
if (ModelState.IsValid)
{
try
{
db.Entry(person).State = EntityState.Added;
db.SaveChanges();
return RedirectToAction("Details");
}
catch (...)
{
...
}
}
return View("Create", new PersonFormViewModel(person, drvLicenceList));
}
And the view:
#model MyApp.ViewModels.PersonFormViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(false, "Errors occured.")
<fieldset>
<legend>Fill in your details</legend>
#Html.LabelFor(model => model.person.last_name)
#Html.TextBoxFor(model => model.person.last_name)
#Html.ValidationMessageFor(model => model.person.last_name, "*")
#Html.HiddenFor(model => model.person.persID)
#foreach (var ctg in (Model.DrivingLicenceList))
{
<input type="checkbox" name="driving_licence" value=ctg.value />#ctg.Text
}
<input type="submit" value="Sauvegarder" class="submit" />
</fieldset>
}
I would use a collection property in order to store the selected driving licence categories (multiple checkboxes can be selected => collection):
public partial class Person
{
public string persID { get; set; }
public string last_name { get; set; }
public string[] driving_licence { get; set; }
}
and then you will need to fix the name of the checkbox in order for it to bind correctly:
#foreach (var ctg in Model.DrivingLicenceList)
{
<input type="checkbox" name="person.driving_licence" value="#ctg.Value" />
#ctg.Text
}
and if you wanted to preserve the selected values you will need to set the checked property accordingly:
#foreach (var ctg in Model.DrivingLicenceList)
{
<input type="checkbox" name="person.driving_licence" value="#ctg.Value" #((Model.person.driving_licence ?? Enumerable.Empty<string>()).Contains(ctg.Value) ? "checked=\"checked\"" : "") />
#ctg.Text
}
This being said, we now have a working solution but it is far from anything I would content myself with and stop here. From now on we could start refactoring this mess in order to comply with C# naming conventions (things like property names start with capital letter, ...), introduce real view models (which do not reference domain models), custom HTML helpers that will generate this checkbox lists to avoid writing loops in the views and hardcoding checkboxes, ...

Render Partial View from within a System.Web.Helpers.WebGrid

I am trying to render a Partial from within a System.Web.Helpers.WebGrid
my model class looks like this:
class GameInfo
{
public List<AppUser> Team1 { get; set; }
public List<AppUser> Team2 { get; set; }
// and more properties
}
class AppUser
{
public string PictureUrl { get; set; }
public string ProfileUrl { get; set; }
public long GamesWon { get; set; }
public long GamesLost { get; set; }
public int Points { get; set; }
// and more properties
}
I want my GridView to show a list of GameInfo's in my grid view.
What is turning out be to be tougher than expected is rendering the Teams (List).
To stay DRY I created a partial view to render a Team (_Team.cstml).
This is my razor code:
#if (Model != null)
{
var webgrid = new WebGrid(source: Model.Games,
rowsPerPage: 10);
<div id="grid">
#webgrid.GetHtml(
columns: webgrid.Columns(
webgrid.Column(header: "Score", format: #<text>#item.Score1/#item.Score1</text>),
webgrid.Column(header: "Team 1", format: (item) =>
{
return "hello sb"; // this line works!
//return Html.Partial("_Team", item.Team1); // this gives an error
})
)
)
</div>
}
Any idea how I can get this to work?
Thank you!
In case someone else runs into this, I managed to solve it this morning.
This works:
webgrid.Column(header: "Team 1", format: (item) =>
{
List<Cuarenta.Web.Models.AppUser> team = ((Cards.Cloud.WebRole.Admin.GameInfo)item.Value).Team1;
return Html.Partial("_Team", team);
})

Resources