In Asp.Net MVC, I have a form for creating Advertisement.
public class AdvertisementViewModel
{
public AdvertisementViewModel()
{
this.StartTime = DateTime.Now;
}
public int Id { get; set; }
public DateTime StartTime { get; set; }
// other properties
}
StartTime does not come from the user, but I set it in the constructor.
In my view, user will populate all the input fields and post the model to controller's ActionMethod, where the model will be saved.
Now in order for the StartTime to be passed to ActionMethod, I am adding it as a hidden field to the view so it would be posted back.
Is there a better way of setting start time, as I don't really need it in the view?
I know I can set it in the post action method, but I have different advertisement types and I have to set the StartTime in multiple places. All of my Advertisement types are derived from a base class where StartTime is defined.
Related
I have read this link: https://www.future-processing.pl/blog/view-code-reuse-techniques-in-asp-net-mvc/
I can not use any of those helper ways...
I have to show on multiple mvc sites this string:
1612-1
That is an inquiry number: 16 is the day of month, 12 the month of year and 1 is the database id. I am sure that will not be the final impl but for now we take it as given.
public class MyViewModel
{
public string City { get; set; }
public string PostalCode { get; set; }
public List<string> ActionItemDescriptions { get; set; }
public string InquiryNumber { get; set; }
}
Where would you create the InquiryNumber?
If I put it inside the razor view I cant reuse it.
Seems business logic to me , so it belongs in the business layer.
Then, from within your controller you:
call the business component which returns the inquiry number
store the number in your view model
pass the view model to the view.
One way you could get an inquiry number, without using a helper, is this:
In a controller, have the following action method:
public ActionResult GetInquiryNumber()
{
// TODO : The code to get the inquiry number.
return Content("1612-1");
}
You can then call that method in any view you like, using the following:
#{ Html.RenderAction("GetInquiryNumber", "Home"); }
Obviously you will need to come up with your own method, and controller, names.
This isn't the ideal way of passing data to a view (using a viewmodel is preferable), but the above approach is an option to you.
I'm trying to get my head around why (data annotation) validation errors are triggering when the page first loads, prior to any Submit/Posts. But more importantly how to fix this.
Reading SO and the interwebs, the reason seems to be model binding triggers validation errors for the view model properties, prior to the view model properties having values. I'm not sure if this is true and what is actually happening, but it sounds legit.
And I've read two workarounds, which sound a bit hacky:
1. Use the ModelState.Clear in the controller action method on the inital page load, OR
2. Initialiase the view model properties in an empty view model constructor. (Yet to confirm this technique)
Both these techniques sound like work-arounds. I'd rather understand what is happening and design my code appropriately.
Have others come across this issue? And if so, what are you doing?
Code as requested. Below you can see the Data Annotation validation on Property1 which is being triggered on initial requests, i.e. first page load.
Controller action method (refactored for simplicity):
public ActionResult Index([Bind(Include = Property1, Property2, Property3, vmclickedSearchButton)] IndexVM vm, string Submit)
{
bool searchButtonClicked = (Submit == "Search") ? true : false;
if (searchButtonClicked)
{
PopulateUIData(vm); // Fetch data from database and pass them to VM
if (ModelState.IsValid)
{
vm.clickedSearchButton = true; // Used in the vm to avoid logic execution duing initial requests
DoWork(vm);
}
}
return View(vm);
}
// Inital request
IndexVM newVM = new IndexVM();
PopulateUIData(newVM); // Fetch data from database and pass to VM
return View(newVM);
}
Design note:
Ideally I would like to sepate the rendering and submiting logic into separate action methods.
I.e. rendering within a [HttpGet]Index() action method, and submitting within a [HttpPost]Index() action method.
But since I'm using ForMethod.Get in the View as this method is used for searching functionality, I can only use a [HttpGet] Index action method.
View Model (refactored for simplicity):
public class IndexVM
{
// DropDownLists
public IEnumerable<SelectListItem> DDLForProperty1 { get; set; }
public IEnumerable<SelectListItem> DDLForProperty2 { get; set; }
public IEnumerable<SelectListItem> DDLForProperty3 { get; set; }
[Required]
public int? Property1 { get; set; }
public int? Property2 { get; set; }
public int? Property3 { get; set; }
public bool vmclickedSearchButton { get; set; }
}
Note:
The view model is very simple. It contains drop down lists, selected properties for the DDLs, and a validation rule on one of the properties.
Adding a constructor to the view model and initialising the property workaround:
public IndexVM()
{
this.Property1 = 0;
}
The problem is that you are sending an invalid model to your view.
The Property1 in your model is being required and is a nullable int. This does not explain why validation executes, but why the model is invalid.
Your action method is executing the validation during initial load. Model binding will execute validation regardless of http method (get or post).
Since you are requiring Property1 (int?) to NOT be null, by definition your model becomes invalid when it is instantiated. There are several ways to handle this (not sure which is most appropriate though)
Create separate methods for HttpGet and HttpPost in your controller. Do not implement binding for HttpGet.
Use a default value (as you have done already)
Modify the model so that Property1 is not nullable (i.e. int).
I have an object that I would like to display in a Details view. The object has a bunch of properties that the view needs.
The object also has parents and grandparents, which I need to display in the view.
What I have for my object viewModel is:
public class ObjectViewModel
{
// Used when creating a new object under a parent object
[HiddenInput(DisplayValue = false)]
public int? ParentObjectId { get; set; }
[Required]
public Object Object { get; set; }
// Info that only the view needs, which is defined in the Controller based on some logic
public string ActiveTitle { get; set; }
// A bre
public IList<Object> ParentObjects { get; set; }
}
I then use this in my Detail controller method:
public ActionResult Detail(int objectId)
{
// TODO: Make this a service call
var object = _db.Objects.FirstOrDefault(s => s.ObjectId == objectId);
if (object == null)
{
return View("Error");
}
var model = new SetViewModel() {
ActiveTitle = object.Name,
Object = object,
ParentObjectId = object.ParentObject.ObjectId,
ParentObjects = _objectService.GetParentObjects(set.ParentObject)
};
return View(model);
}
Does this look right? Or should I be pulling the required fields from the Object model into the viewModel, and not the objects themselves?
To have an object type in your view model is super vague and your code would be hard to support if you are not the original programmer. I would Add the class type to the actual model or use generics to specify the class type as shown below:
public class ObjectViewModel<T>
{
// Used when creating a new object under a parent object
[HiddenInput(DisplayValue = false)]
public int? ParentObjectId { get; set; }
[Required]
public T Object { get; set; }
// Info that only the view needs, which is defined in the Controller based on some logic
public string ActiveTitle { get; set; }
// A bre
public IList<T> ParentObjects { get; set; }
}
Either option will work, and you will often have a mixture of both techniques in a given application.
The key idea is that your view model should contain what the view needs in order to display the data to the user.
If your view merely displays the individual, primitive fields in simply controls, e.g. a series of labels or textbox controls, then your view model should probably specify only the fields, and not the parent object.
However, it's very possible for your view to include a templated or custom control that "knows how" to display a complex object in its entirety. In that case, your view model would need to include the entire object. (In practice I find myself doing this much more often in WPF than ASP-MVC but I've done both).
It looks like the answer will be contextual. Many teams using layered architectures might adopt architectural conventions whereby layers below X should not be referenced directly by your views, and a data access class might be a likely candidate for such a restriction. In your case, it does look like you will be binding your view's structure to the structure directly to your database schema (assuming, since you're using "_db"), which might be considered unreasonably tight coupling.
Also, I'm assuming you're using "object" to represent "any general thing" rather than literally a System.Object, since your objects appear to have an ObjectId property in your lambda expression.
Has anyone successfully bound 2 textboxes to one DateTime property using the model binding in MVC, I tried Scott's method http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx but was dissatisfied as this stops the HTML fields and Model properties having the same name (so the validation could not set the correct css if it failed).
My current attempt modifies this by removing the ValueProviderResult object from the bindingcontext and the adding a new one for the key made up from the date result and a tiem (using the .Time convention in Scotts post) but I am a little wary of messing around with the bindingContext object direct.
The idea is that i can use IDateErrorInfo and VAB PropertyComparisonValidator to compare 2 datetimes on the model where one needs to be later than the other, to do this the time element needs to be included.
I use a different approach and go for two different sets of models: My view model would have two properties and the validation for those fields, while my domain model would have one DateTime. Then after the binding, I let the view model update the domain:
public ActionResult Update(DateInput date)
{
if(date.IsValid)
{
var domain = someRepository.GetDomainObject(); // not exactly, but you get the idea.
date.Update(domain);
}
// ...
}
public class DateInput
{
public string Date { get; set; }
public string Time { get; set; }
public void Update(DomainObject domain) { ... }
}
public class DomainObject
{
public DateTime SomePointInTime { get; set; }
}
Does it make sense create an object that contains only those properties that the user will input on the webpage, use that for binding in the controller, and then map to the full Entity Object? Or should you just use the entity object, and use Include and Exclude to make restrictions on what gets bound on input?
I have come to like the idea of using interfaces to segregate which properties should be included when the object is updated.
For example:
To create and update an person object:
interface ICreatePerson
{
string Name { get; set; }
string Sex { get; set; }
int Age { get; set; }
}
interface IUpdatePerson
{
string Name { get; set; }
}
class Person : ICreatePerson, IUpdatePerson
{
public int Id { get; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
Then, when binding model, just use the appropriate interface as the type and it will only update the name property.
Here is an example controller method:
public ActionResult Edit(int id, FormCollection collection)
{
// Get orig person from db
var person = this.personService.Get(id);
try
{
// Update person from web form
UpdateModel<IUpdatePerson>(person);
// Save person to db
this.personService.Update(person);
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelErrors((person.GetRuleViolations());
return View(person);
}
}
See this article (and the comments) for a very good discussion of the options.
I recommend using a separate presentation model type in most cases. Aside from the issue of binding (which is important, but there are other ways around this issue), I think that there are other reasons why using presentation model types is a good idea:
Presentation Models allow "view-first" development. Create a view and a presentation model at the same time. Get your user representative to give you feedback on the view. Iterate until you're both happy. Finally, solve the problem of mapping this back to the "real" model.
Presentation Models remove dependencies that the "real" model might have, allowing easier unit testing of controllers.
Presentation Models will have the same "shape" as the view itself. So you don't have to write code in the view to deal with navigating into "detail objects" and the like.
Some models cannot be used in an action result. For example, an object graph which contains cycles cannot be serialized to JSON.