I'm looking for a way to achieve the following in MVC 3.
Let's say I have a page with one question. On a post, I would like to bind the following ViewModel:
public class QuestionElementViewModel
{
public int QuestionId { get; set; }
public string Name { get ; set; }
public string Question { get; set; }
public string Feedback { get; set; }
}
This can easily be done like this (if I use the correct names in the View):
[HttpPost]
public ActionResult Index(QuestionElementViewModel pm)
{
//Do something
}
Now I have multiple questions on my page. Using the technique explained here: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx I can also make this quite easy:
[HttpPost]
public ActionResult Index(QuestionElementViewModel[] pm)
{
//Do Something
}
But lets say I don't have only questions, but different elements on my page and these elements can vary. Would it be somehow possible to achieve something like this:
[HttpPost]
public ActionResult Index(IElementViewModel[] pm)
{
//Do Something
}
where every ViewModel that implements this interface is automatically bound?
I've tried this code and it results in an error: Cannot create instance of an interface, which sounds pretty obvious.
I think i should create a custom model-binder, but I'm not very familiar with that and I don't want to step away from the standard MVC-framework too much..
You will need a custom model binder for this scenario because you are using an interface and the default model binder wouldn't know which implementation to instantiate. So one possible technique is to use a hidden field containing the concrete type for each element. Here's an example that might put you on the right track.
Related
I want to accept different model type from body based on query param value.
Example:
[HttpGet]
[Route("GetSystemdetails")]
public string Getdeatils([FromBody] SystemDetail sysdetails, string type)
{
//some code here
string details = getdetails(sysdetails);
}
// abc model
public class abc
{
public int UserID { get; set; }
public string Email { get; set; }
}
//xyz model
public class xyz
{
public int xyzid { get; set; }
public string systemval { get; set; }
public string snum { get; set; }
}
type abc and xyz will have it's own model. So based on type I receive in query param I wanted to pick the model and proceed.
Sample url:
localhost/GetSystemdetails/type=abc
localhost/GetSystemdetails/type=xyz
I thought of creating a new model SystemDetail which holds these two models(xyz and abc) and based on system pick them.
I wanted to know what are possible ways to achieve this kind of requirements without creating multiple methods in controller(I don't want to change the format of the URL).
That's not something that's supported out of the box. Your linked solution is probably the closest you'll get to that.
ASP.NET Core is not supposed to take values of the parameters into account when routing, except for validation.
There are several possible ways to do so
Having multiple model objects
As in the link you provided, you can declare multiple model objects. The site has given the example of
public class PostUserGCM
{
public User User { get; set; }
public GCM GCM { get; set; }
}
but you can use your own examples.
Base model
Your models can inherit from some base model. If you only need a single model at a time and they share some similarities, then you could just create a base model which the other two are inheriting from, be agnostic at implementation time and your use cases will mainly differ on instantiation inside the controller, while some service methods could handle other differences.
I'm fairly new to ninject so you'll have to forgive the potentially stupid question. I have been able to successfully bind my own custom filter to controller actions, however my question is can I do the same to a property on a ViewModel? My scenario is thus:
I have a view model with properties that look like this
public class CreateViewModel
{
...
[PopulateWith(typeof(Country))]
public IEnumerable<SelectListItem> Countries { get; set; }
...
}
the attribute is is a simple class
public class PopulateWithAttribute : Attribute
{
public Type Type { get; }
public PopulateWithAttribute(Type t)
{
Type = t;
}
}
and all I want to be able to do is have a block of code that will run when a new instance of CreateViewModel is created, that will take the database context to hydrate the enumeration. I'm not sure if even an action filter is the correct route to go down like how you make custom authorization / logging functionality. It doesn't seem that the BindFilter<> has anything that points to being able to bind on properties...
A point in any direction or to any resources would be great.
I have a partial view that displays a number of inputs based on a view model. In some situations, some of those inputs are not rendered by the partial view, but are still decorated with [Required] attributes in the view model. As a result, when the form is posted back to my controller, ModelState.IsValid returns false. Is there a way to bypass this?
You can use Foolproof to validate your fields conditionally. This way, they'll be required only when they need to, as you can see in the example of the link.
private class Person
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public bool Married { get; set; }
[RequiredIfTrue("Married")]
public string MaidenName { get; set; }
}
In this example, MaidenName will only change your ModelState.IsValid to false if Married == true
I'd recommend separating your validation from your base model.
public class MyModel
{
public string MyString { get; set; }
public string MyHiddenField { get; set; }
}
public interface IMyModel_ValidateMystringOnly
{
[Required]
string MyString { get; set; }
}
[MetadataType(TypeOf(IMyModel_ValidateMystringOnly))]
public class MyModel_ValidateMystringOnly : MyModel
This allows you to create any number of validation types, and only validate what you want when you want.
public ActionResult ShowMyModel()
{
var model = new MyModel(); // or Respository.GetMyModel() whatever..
View(model);
}
public ActionResult ValidateModel(MyModel_ValidateMystringOnly model)
{
if (ModelState.IsValid)
{
// Hey Validation!
}
// MyModel_ValidateMyStringOnly is a MyModel
// so it can be passed to the same view!
return View("ShowMyModel", model);
}
This is just an example, but should be clear on how-to reuse the same model with or without validation.
I have used method at times where the form changes slightly based on specific DropDown or Radio Button selections.
Inside your Action method before you check ModelState.IsValid you can do something like ModelState.Remove("Object.PropertyName")
Note: The property name should be the same as the ID rendered to the client. Use a "." for any underscores.
If isSomeCondition Then
ModelState.Remove("Property1")
ModelState.Remove("Property2")
End If
If ModelState.IsValid() Then
...
End If
You should always separate your VIEW model from your DOMAIN model. There is a very good reason for this and it has to do with security. When you use your domain models as your view models you are vulnerable to an overposting and/or underposting attacks. You can read more about it on these pages:
http://odetocode.com/blogs/scott/archive/2012/03/12/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx
https://hendryluk.wordpress.com/tag/asp-net-mvc/
In short if you don't need a field then it should not be in your view model. You should convert - map your view models to domain models. Although it can be tedious it makes your application much more secure. There are libraries you can use to help you with mapping such as Automapper.
EDIT: Since my original answer, I have come to a conclusion that the easiest way to deal with this type of scenario is to have your view model implement IValidatableObject interface and then write your validation logic inside the Validate method. It does not give you client side validation but it is the most effective and clean way to accomplish custom/scenario based validation without writing your own custom filters.
You can read more about it here: http://weblogs.asp.net/scottgu/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3
I have a slightly long conceptual question I'm wondering if somebody could help me out with.
In MVC I've built a website which builds grids using kendoui's framework.
All the grids on my website are constructed exactly the same except for the model they use and the CRUD methods that need to be implemented for each model. I set things up where each Model implement an interface for CRUD methods like below to get the logic all in one place.
//Actual interface has variables getting passed
public interface IKendoModelInterface
{
void Save();
void Read();
void Delete();
}
public class Model1: IKendoModelInterface
{
[Key]
public int IdProperty1 { get; set; }
public int SomeProperty2 { get; set; }
public string SomeProperty3 { get; set; }
public void Save(){
//Implement Save
}
public void Read(){
//Implement Read
}
public void Delete(){
//Implement Delete
}
}
Then to speed up the writing of all the scaffolding Action methods needed to get the grids to work I created an abstract Controller that can call the interface methods of the Model that gets passed into it.
//Implement the AJAX methods called by the grid
public abstract class KendoGridImplController<T> : Controller where T : class, IKendoModelInterface
{
// Method called from kendo grid
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords)
{
//Invoke Create Method for Model and return results
}
public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request, int Id)
{
//Invoke read method for model and return results
}
//Update and Delete also implemented..
}
Then I just need a Controller per model that implements the abstract controller above passing in the type of Model being used.
public class ResponsibilityMatrixController : KendoGridImplController<Model1>
{
//Set up the page the grid will be on
public ActionResult Index(int id)
{
return View("SharedGridView", id);
}
//Can override abstract methods if needed but usually won't need to
}
I'm wondering if I can take this one step further or if I've reached the end of the road. To me it just seems like more repeated code if I have to create a controller per Model that does nothing but pass in the type to the abstract controller and calls the same View.
I attempted for quite a while yesterday to figure out if I could dynamically assign the type to the abstract controller. I setup something where I was sending back the type of model via strings and I could still invoke the methods needed. Where it failed, was that the mapping could no longer be done on any of the controller actions by default since the type isn't known at compile time. eg
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords)
createdRecords can't be bound like this if T that's passed in is an interface and not the Model itself and I've found no real way to map the form data to an instance of a type that isn't known at compile time.
I'm wondering if there's an easy way to do this mapping between an instance of the type of object getting passed in that I can figure out at runtime, if there's some other way to set this up that I'm overlooking or if both those things are going to be way too much work and I should just not attempt something like this and build a controller per model like I do now?
In case anybody else finds this in the future here's what I've done so far to solve my issue. First I downloaded the impromptu-interface code lib which is incredibly helpful when dealing with dynamic types.
Then for the abstract controller's save methods where it was important that I could bind back to the original object type I did this.
// Method called from kendo grid
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ExpandoObject> createdRecords)
{
Type originalGridType = GetTypeOfModelUsingCustomCodeIDevelopedEarlier();
foreach (ExpandoObject record in createdRecords)
{
var convertedType = Impromptu.InvokeConvert(record, originalGridType);
T objectInstance = Impromptu.ActLike(convertedType);
objectInstance.Save();
}
}
Then I just needed to add a cast in my model that could convert from the ExpandoObject to my model. An extra method that I still wish didn't have to be there but with some helper methods that I wrote it's not a lot more code to make happen.
public static implicit operator Model1(ExpandoObject expando)
{
Model1 model = new Model1();
//Set fields of model...
//....
return model;
}
From here everything works front to back. Maybe there's a better way but this is the best I could come up with so far.
I have a set of model classes from another section of the application that cannot be modified. These do not have the validation attributes I need (RemoteAttribute for instance). How do I go about adding these? I can't add [MetadataTypeAttribute] to models.
To illustrate:
//in Models.dll
//remember: I can't modify this
public class Product
{
string Name { get; set; }
}
//in Web.dll
public class ProductController
{
// GET: /Product/
public ActionResult Index()
{
return View(new Product());
}
}
//what i need:
public class ProductMetadata
{
[Remote("Foo", "Bar")]
[RegularExpression]
string Name { get; set; }
}
Is this in any way possible without creating a ViewModel class or something of that sort?
Is this in any way possible without creating a ViewModel class
Assuming that a properly architected ASP.NET MVC application should always use view models you can only benefit from introducing them. In addition to solving this particular problem and hundreds of potential other problems you will have a properly architected ASP.NET MVC application :-)
Tying your model to a controller (which is what the RemoteAttribute will do) seems like a horrible idea in terms of reusability of this model in other applications.