Template with Required Attribute Knowledge - html

This seems very basic but I'm struggling to find a solution I'm happy with at the minute. All I want to do is add a class with the name "Required" to any fields that have a required property against them so:
public class Dummy{
[Required]
public string Name {get; set;}
}
Would be called with
#Html.EditorFor(model=>model.Name)
and would output something like
<input id="Name *Data-VAL and other attribs* class="Required" />
With all the inbuilt unobtrusive goodness etc. I'm using Razor and MVC 3. Any help much appretiated

You may take a look at the following blog post which explains how you could write a custom DataAnnotationsModelMetadataProvider to achieve this.

using System.ComponentModel.DataAnnotations; //You need to import this namespace
public class Dummy {
[Required]
public string Name { get; set; }
}
Further reference: http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs

Related

.NET Core Controller inheritance

I looked for this question, and altough there are similar questions asked, I could not find an answer.
So I have a problem. I have 2 classes:
public class Person {
public string name{ get; set; }
}
public class Doctor: Person{
public string specialization{ get; set; }
}
And I have controller:
[HttpPost]
...
public virtual IActionResult PostPerson([FromBody]Person person)
{ ... }
How can I make it so that if I send JSON like this:
{"specialization":"obgyn"}
that I get Doctor object in my controller?
Do I need to make custom binding (is there an example? however I have much much more classes like this (100ts) so I would not like to do it for each class specifically) or set JsonOptions in Startup.cs, or something third??
Thank you.
So the way to get this working is t oadd in your Startup.cs file a JSonOptions:
opts.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All;
This would then add $type properties to response, and would also read $type from incoming Json Messages. Unfortunatly, my clients wish changed because he does not want to identify the class by that field, but a custom another one, so this solution is not for me, but the answer my still help someone

MVVMCrosscore binding issue tableview, collection

Following is the Observable collection which is available in the viewmodel:
ObservableCollection<Category> productcat;
further split of Category class is as follows:
public class Category
{
public string CategoryName { get; set;}
public List<ProductData> Products
{
get;
set;
}
}
ProductData class as follows:
public class ProductData
{
public string ProductImageUri { get; set;}
public string ProductTitle { get; set;}
public float productcost { get; set;}
}
Part 1:
Now I have UIScrollView where each Scrollbar item is a button item, containing title as the CategoryName.
I want to do the binding of CategoryName from the observable collection- to each scrollbar button title
Whenever the collection changes the buttons in the UISCrollView titles must reflect the change. What would be the binding expression in this case given the above class structures. Its challenging to figure out binding syntax.
Part 2:
I have a UITableView which would contain a cell having product title, product image and product cost, which means i have list
I want to bind this UITableView to this list which is part of Observable Collection->CategoryName->ProductData list
What would be the binding expression in this case. I hope we must do custom binding here.?
Yes as you said MvxTableViewCell etc., are available.
And regarding custom binding should I do it in the minisetup?
view models/data structures
In your data structures, you seem to be binding public fields instead of public properties.
These won't work straight away - you need to use properties
So:
public string CategoryName;
public class ProductData
{
public string ProductImageUri;
public string ProductTitle;
public float productcost;
}
need to become:
public string CategoryName {get;set;}
public class ProductData
{
public string ProductImageUri {get;set;}
public string ProductTitle {get;set;}
public float productcost {get;set;}
}
I am not able to find any of these classes: MvxCollectionViewSource, MvxTableViewCell, MvxCollectionViewController etc
MvxCollectionViewSource and MvxTableViewCell should be available in MvvmCross.Binding.Touch.dll
MvxCollectionViewController is not available - it's an MvvmCross View
In this case how can I achieve binding in CrossCore environment?
This is shown in the N+1 N=39 tutorial - http://slodge.blogspot.com.au/2013/09/n39-crosslight-on-xamariniosmonotouch.html - with source in https://github.com/slodge/NPlus1DaysOfMvvmCross/tree/master/N-39-CrossLight-Touch
Also I should be able to do custom bindings?
Yes
But I am not having any setup class.. in my case. How can achieve custom binding in this case?
As shown in the N+1 N=39 tutorial, you still have a setup class - so you can put your initialization code in there. After the binding builder has been initialized, you can access the IMvxTargetBindingFactoryRegistry using Mvx.Resolve<IMvxTargetBindingFactoryRegistry>()
Because you are not using MvvmCross - because you are choosing to build your own framework - then ensuring setup is done is your own job to do.
What I am currently doing is have a view class and derive the view from IMvxBindable that's all and doing some binding in it
I have no idea what this means - please try including a working code sample in your questions.

Handling references in breezejs

We are developing a single page app using ASP.NET MVC4 with Web Api + Ko + Breeze using EF Code First.
Our (simplified) data model looks like this
class Product {
public String Name { get; set; }
public ICollection<ImageCollection> ImageSets { get; set;}
public Image DefaultImage { get; set; }
}
class ImageCollection {
public ICollection<Image> Images { get; set; }
}
class Image {
public String ImageUrl { get; set; }
}
DefaultImage is a navigation property (with foreign key) and is one of the images in the ImageSets.
We are exposing a Web API method of Products() and with default Breeze configuration. JSON serialized output on the wire has references for objects (i.e., PreserveReferencesHandling.Object) so when I want to bind the ImageUrl ko is unable to resolve the value.
Html looks like this
<img data-bind="attr: { src: DefaultImage().ImageUrl, title: Name}" />
When I switch the serializer to do PreserveReferencesHandling.None, the binding works.
Question: how do I make the default config to work? or if I switch to PreserveReferencesHandling.None for Breeze what are the gotchas/downsides?
Thanks!
In general, you do NOT want to switch PreserveReferencesHandling to None because you will lose the ability to serialize circular references and your payloads will get much larger.
I don't actually understand why your binding would begin to work after setting this. The first step to understanding this is probably to check that the ko objects actually contain the correct data after your query.
Remember that breeze navigation properties are lazy-loaded, so you may not have loaded them with your initial query. Take a look at the "EntityAspect.loadNavigationProperty" method.

Entity Type Has No Key Defined

Another 'Entity Type 'x' has no key defined' question, but I've set the [Key] attribute on a property so I'm a bit confused.
Here's my entity and context classes:
namespace DoctorDB.Models
{
public class Doctor
{
[Key]
public string GMCNumber;
[Required]
public string givenName;
[Required]
public string familyName;
public string MDUNumber;
public DateTime MDUExpiry;
public string MDUCover;
}
public class DoctorContext : DbContext
{
public DbSet<Doctor> Doctors { get; set; }
}
}
When I go to create my controller, I've selected to create it with the Entity Framework methods using this entity and context:
and I get this error:
My only thought is whether you can't successfully use [Key] on a string property. If you can't then fair enough, I'll work round it, but I'd be grateful if someone could confirm this one way or the other.
You need to change GMCNumber to a property not a field.
To help clarify, this line:
public string GMCNumber;
needs to become:
public string GMCNumber { get; set; }
I encountered the same error message when I had defined the property as private.
I ran into this post after facing a similar issue today. The problem was that I was attempting to create the scaffold after adding the [Key] attribute to my model and without compiling. Once I compiled with the [Key] attribute the scaffolding generated just fine.

Cannot get my html input array to serialize into a List<string> in Asp.Net mvc

I am attempting to implement a tagging system into my asp.net MVC project. When a user edits or adds a task, they can add any amount of tags they want before submitting. I am using the Jquery Tagit plugin, so when a user adds a new tag an input field is created that looks like:
<input type="hidden" style="display:none;" value="tag1" name="Tags[]">
When the user presses the submit button after adding a few tags, the browser sends the following querystring to the server (retrieved via fiddler):
IsNew=True&Id=2222&Title=Test+Title&Description=Test+Description&Tags%5B%5D=Tag1&Tags%5B%5D=blah&Tags%5B%5D=another-tag
Now my viewmodel that I am serializing this data into has the following structure:
public class KnowledgeBaseTaskViewModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings=false, ErrorMessage="Task title is required")]
[StringLength(500)]
public string Title { get; set; }
[Required(AllowEmptyStrings=false, ErrorMessage="Task description is required")]
[StringLength(500)]
public string Description { get; set; }
public List<string> Tags { get; set; }
public bool IsNew { get; set; } // Needed to determine if we are inserting or not
}
Finally my receiving action has the following signature:
[HttpPost]
public ActionResult EditTask(KnowledgeBaseTaskViewModel task)
The issue is that my tag list is not serializing correctly, and my List Tags is null. I have looked at various questions on this site on how to serialize arrays but I still cannot see what I am doing wrong. Any help is greatly appreciated.
It sounds like what you've got should work, but try changing the type of Tags property from List to IList. the model binder might not be using the concrete List<> type.
also, check out this article by Phil Haack: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx