How could i dynamically bind data in checkbox in mvc3 razor - asp.net-mvc-3

I am working in mvc3 razor.
i want checkbox input in razor view for all catagories stored in database.
how could i bind it? please help

Suppose your model is having a field to hold all the checkbox text like.
public class MyClass
{
public string SelectedOptions {get;set;}
public List<String> CheckList {get;set;}
}
Write a controller Action method like
public ActionResult ShowCheckBoxList()
{
MyClass Options= new MyClass();
Options.CheckList = new List<String>();
// Here populate the CheckList with what ever value you have to
// either if you are getting it from database or hardcoding
return View(Options);
}
you have to create a view by right clicking the above method and choose Add View. Make sure you keep the name same as the method name also you the strongly typed view by choosing the MyClass Model from the dropDown, scaffolding template is optional use it as per your scenario.
Now in your View you can use this populated check box text as
#foreach(var optionText in Model.CheckList)
{
#Html.CheckBox(#Model.SelectedOptions, false, new {Name = "SelectedOptions", Value = #optionText})
#Html.Label(#optionText , new { style = "display:inline;" })
}
Keep this in a form and make sure you also specify a Action to be called on post of the form.
Make your action name same as the previous action (it is [GET] meaning before post), Now we create same method for [POST]
[HTTPPOST]
public ActionResult ShowCheckBoxList(MyClass data) // here you will get all the values from UI in data variable
{
//data.SelectedOptions will have all the selected values from checkbox
}

Related

Cannot Populate TextBox in MVC

public IActionResult Create() { ViewData["StateId"] = new SelectList(_context.States, "Id", "Abbreviation")
ViewData["UserId"] = Guid.NewGuid().ToString(); return View(); }
I have the above code where I need to populate a dropdown list with some States e.g. Alabama etc.
Then I need to populate a textbox with a UserID(new Guid). This code is in my controller in the part that a new user is created. The code populates the dropdown list but not the textbox.
Any idea why?

MVC3 Razor - Models and Views

I have an action that creates a List and returns it to my view..
public ActionResult GetCustomers()
{
return PartialView("~/Views/Shared/DisplayTemplates/Customers.cshtml", UserQueries.GetCustomers(SiteInfo.Current.Id));
}
And in the "~/Views/Shared/DisplayTemplates/Customers.cshtml" view I have the following:
#model IEnumerable<FishEye.Models.CustomerModel>
#Html.DisplayForModel("Customer")
Then I have in the "~/Views/Shared/DisplayTemplates/Customer.cshtml" view:
#model FishEye.Models.CustomerModel
#Model.Profile.FirstName
I am getting the error:
The model item passed into the dictionary is of type System.Collections.Generic.List`1[Models.CustomerModel]', but this dictionary requires a model item of type 'Models.CustomerModel'.
Shouldn't it display the Customer.cshtml for every item in the collection in the Customers.cshtml?
Help!
I am not sure why you are calling a partial view like this. If it is a Customer Specific view, why not put it under Views/Customer folder ? Remember ASP.NET MVC is more of Conventions. so i would always stick with the conventions (unless abosultely necessary to configure myself) to keep it simple.
To handle this situation, i would do it in this way,
a Customer and CustomerList model/Videmodel
public class CustomerList
{
public List<Customer> Customers { get; set; }
//Other Properties as you wish also
}
public class Customer
{
public string Name { get; set; }
}
And in the action method, i would return an object of CustomerList class
CustomerList customerList = new CustomerList();
customerList.Customers = new List<Customer>();
customerList.Customers.Add(new Customer { Name = "Malibu" });
// you may replace the above manual adding with a db call.
return View("CustomerList", customerList);
Now there should be a view called CustomerList.cshtml under Views/YourControllerName/ folder. That view should look like this
#model CustomerList
<p>List of Customers</p>
#Html.DisplayFor(x=>x.Customers)
Have a view called Customer.cshtml under Views/Shared/DisplayTemplates with this content
#model Customer
<h2>#Model.Name</h2>
This will give you the desired output.
Your view is expecting a single model:
#model FishEye.Models.CustomerModel // <--- Just one of me
You're passing it an anonymous List:
... , UserQueries.GetCustomers(SiteInfo.Current.Id) // <--- Many of me
You should change your view to accept the List or determine which item in the list is supposed to be used before passing it into the View. Keep in mind, a list with 1 item is still a list and the View is not allowed to guess.

What order are objects placed into a Model in MVC3 and how can I control it

I have an model being passed back successfully from my view except that I would like an ID value to be the first thing that is bound back to the Model so it can fill some information from the db. The information being passed back is as follows
SetupID:91c16e34-cf7d-e111-9b66-d067e53b2ed6
SwayBarLinkLengthLF:
SwayBarLinkLengthRF:
.....way more information....
My Action is as follows
[HttpPostAttribute]
public ActionResult SaveSetup(SetupAggregate setup)
{
setup.SaveSetup();
return null;
}
I would like the SetupID to be the first property that is set on the empty setup object but it looks like the first property alphabetically is being set first.
In my opinion you really need to be working with 2 separate "models" - your ViewModel, which is what is in your MVC project and is rendered to your view. And a 2nd EntityModel in a business logic layer. This is standard "enterprise" programming design. It gives you a lot more control of your data. The idea is this.
UI Assembly (MVC project)
ViewModel definition
public class MyModel {
public int ID { get; set; }
.... // bunch of other properties
}
Controller
public class InterestingController : Controller {
public ActionResult CreateNewWidget() {
var model = new MyModel();
return View(model);
}
[HttpPost]
public ActionResult CreateNewWidget(MyModel model) {
if(ModelState.IsValid) {
// your ctor can define the order of your properties being sent in and you can set the entity values in the ctor body however you choose to. Note never SET an ID/Primary key on a Create, let the DB handle that. If you need to return the new Key value, get it from the insert proc method in your DAL and return it up the stack
var entityModel = new EntityFromBLL(model.Name, model.OtherProperty, ... etc);
entityModel.Save(User.Identity.Name); // your save method should always capture WHO is doing the action
}
return View(model);
}
public ActionResult UpdateExistingWidget(int id) {
var entityModel = new EntityFromBLL(id); // get the existing entity from the DB
var model = new MyModel(entityModel.ID, entityModel.Name, ... etc); // populate your ViewModel with your EntityModel data in the ViewModel ctor - note remember to also create a parameterless default ctor in your ViewModel as well anytime you create a ctor in a ViewModel that accepts parameters
return View(model);
}
[HttpPost]
public ActionResult UpdateExistingWidget(MyModel model) {
if(ModelState.IsValid) {
var entityModel = new EntityFromBLL(model.ID); // always pull back your original data from the DB, in case you deal with concurrency issues
// now go thru and update the EntityModel with your new ViewModel data
entityModel.Name = model.Name;
//... etc set all the rest of the properties
// then call the save
entityModel.Save(User.Identity.Name);
}
return View(model)
}
}
Your Entity Model should be defined with private fields, public properties, a ctor that takes in all required fields for an insert (minus the primary key), a ctor that takes in the primary key and then can call an internal load method statically to return a populated object. Business rules and property validation and a single Save method. The Save method should check for the IsDirty bit after all the properties have been set and call the respective Insert or Update methods .. which in turn should call into a DAL passing DTOs

A `ViewModel` for each page (`Create.cshtml` and `Edit.cshtml`)?

Questions
There are actually two related questions:
Should I create a ViewModel for each page?
If you do not have problems in creating a single ViewModel class for the two pages (Create.cshtml and Edit.cshtml) how can I validate the ViewModel in different ways (depending on the page that is being used)
Source
ViewModel
public class ProjectViewModel
{
public string Name { get; set; }
public string Url { get; set; }
public string Description { get; set; }
}
Edit.cshtml
#using BindSolution.ViewModel.Project
#model ProjectViewModel
#{
ViewBag.Title = Model.Name;
}
#Html.EditorForModel()
Create.cshtml
#using BindSolution.ViewModel.Project
#model ProjectViewModel
#{
ViewBag.Title = "New Project";
}
#Html.EditorForModel()
ProjectValidator.cs
public class ProjectValidator : AbstractValidator<ProjectViewModel>
{
private readonly IProjectService _projectService;
public ProjectValidator(IProjectService projectService)
{
_projectService = projectService;
RuleFor(p => p.Name)
.NotEmpty().WithMessage("required field")
/*The validation should be made only if the page is Create.cshtml. That is, if you are creating a new project.*/
.When(p => p.??) //Problem Here!!
.Must(n => !_projectService.Exist(n)).WithMessage("name already exists");
RuleFor(p => p.Url)
.NotEmpty().WithMessage("required field");
}
}
Note that if the user is editing an existing project, validation of the property name should not be done again.
ProjectController.cs > Edit method
[HttpPost]
public ActionResult Edit(Guid projectID, ProjectViewModel model)
{
var project = _projectService.Repository.Get(projectID);
if (ModelState.IsValid && TryUpdateModel(project))
{
_projectService.Repository.Attach(project);
if (_projectImageWrap.Create(project) && _projectService.Repository.Save() > 0)
return AjaxRedirect("Index");
}
return View(model);
}
Notes
If I create a ViewModel for each page, there is a duplication of code since pages have the same properties.
Add a property on the ViewModel indicating what page it is being displayed does not solve my problem as to instantiate the ViewModel, I use AutoMapper.
To validate the data, I use FluentValidator.
Thank you all for your help!
My understanding is that there isn't a 1:1 correlation between ViewModels and Views. Oftentimes you will have a View that will not require a ViewModel to go alongside with it.
You will want to create a ViewModel if and only if you need a Model absolutely paralleled and tailored to a specific View. This will not be the case 100% of the time.
When the functionality / use case /validation is different between the pages I use different models. If its the exact same besides the presence of an ID or something similar I use the same model, and its also possible to just use the same view if the differences are pretty minor.
Since your validation is different, if I were doing it I would create two different models so that I could use the out of the box DataAnnotations, with your validation though it may not be required. You could also on the edit model have a readonly property for name since its not editable any longer.
For me the same object must have the same validation on every time, in main to ensure the consistence of the object, independently if it was created or edited.
i think that you should create only one validation, and edit your "exists" method to pass to verify if it is a new object or the current object in repository.
Personally, I don't have a problem with 2 view models, especially if (as Paul Tyng suggested) you use a base class for the fields that are common to edit and create scenarios.
However, if you really only want a single view model then you would either need to:
add a flag to the view model and use the When() method in your validator. Note though that this will not generate the appropriate client-side only validation
define a second validator and invoke the appropriate one from the controller (i.e. instead of the "automatic" validation)
Provide another view Edit.cshtml which will allow the user to edit the data for a selected item.
Create another view Query.cshtml which based on the ItemName will allow the users to query the Inventory table.
Perform the calculation for the total profit (numbersold times (saleprice-purchasecost). Display the total profit.
(BONUS) Create another view Sell.cshtml that will indicate the sale of an item. Adding one to NumberSold and subtract one from NumberInventory for the selected record.

MVC - Dealing with the model and events on the page

I have what is probably a basic question regarding how to structure an MVC page.
Assume this is my model:
public class MyModel
{
int ProductId
List<ParameterTable> ParameterTables
...
[other properties]
...
}
ProductId initially won't have a value, but when its value is selected from a DropDownList it will trigger an event that retrieves the List items associated with that product.
My problem is when I do this AJAX call to get the parameter tables I'm not sure how to handle the response. I've only seen examples where people then manually inserted this data into the page via the jquery. This would mean handling displaying the data in your view (for the first time loading the page) and in the jquery (whenever it changes).
I am wondering if there's a way to somehow pass back a model of sorts that binds my return value of List into my page without needing to specify what to do with each value.
Would I have to have the changing of the ProductId DropDownList trigger an ActionResult that would reload the whole page to do this instead of a JsonResult?
You could return a partial view with your ajax call.
Controller action:
public ActionResult Filter(int productId) {
var product = _repository.Find(productId);
if (Request.IsAjaxRequest())
{
return PartialView("_Product", product);
}
else
{
return View(product);
}
}

Resources