Cannot Populate TextBox in MVC - model-view-controller

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?

Related

Passing data from Controller to model in MVC 3

is there a way to pass data from controller to model?
the scenario of my project is that, it has two tables in database, and in View there are two text boxes , the data of one text box is save to one table while data of another table is save to another table , i want to show the data of both tables in another single View . for that reason i want to send both textbox values from controller to model then want to show the data from that model to the view.
can someone please help how can i implement it ?
You need to create a view model and use that. view model's are simple POCO classes which are specific to the view.
public class CustomerInfo
{
public string Name {set;get;}
public string AddressLine {set;get;}
}
And in your GET Action, you can create an object of this, read the data from 2 tables and set the property values of our view model and send to the view
public ActionResult View(int id)
{
var vm = new CustomerInfo();
var db=new YourDbContext();
var customer=db.GetCustomer(id); // read from first table
var address=db.GetAddress(id); // read from second table
vm.Name = customer.FirstName;
vm.AdddressLine = address.AddressLine1;
return View(vm);
}
And your view will be strongly typed to this view model
#model CustomerInfo
<h2>#Model.Name</h2>
<h3>#Model.AddressLine1</h3>
If you are trying to save this information to the db tables, You may have a form in your view
#model CustomerInfo
#using(Html.BeginForm("Edit","Home"))
{
<label>Name</label> #Html.TextBoxFor(f=>f.Name)
<label>Name</label> #Html.TextBoxFor(f=>f.AddressLine)
<input type="submit" />
}
and in your HttpPost action
[HttpPost]
public ActionResult Edit(CustomerInfo model)
{
// read the values from model and save to 2 tables
var c=new Customer { FirstName=model.Name};
var a=new Address{ AddressLine1=model.AddressLine};
var db=new YourDbContext();
db.Customers.Add(c);
db.Addresses.Add(a);
db.SaveChanges();
return RedirecToAction("Success");
}
If you want to save a collection of items, You may refer this answer or this.

How could i dynamically bind data in checkbox in mvc3 razor

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
}

MVC dropdownlist , data not displaying when model is not Ienumerable

I am having a problem passing to the View a Model that contains the dropdown data and the model.
With this code my page loads, but the dropdownlist contains "System.Web.MVC.SelectList" when selected.
Here's my controller code.
public ActionResult Index(string productNameFilter, string productCategoryFilter, String productTypeFilter )
{
var ddl = new Items();
ddl.CategoryddList = itemsRepository.GetItemDdl("Item Categories").Select(c => new SelectListItem
{
Value = c.DropdownID.ToString(),
Text = c.DropdownText
});
ViewBag.CategoryDD = new SelectList(ddl.CategoryddList, "Value", "Text");
var model = itemsRepository.GetItemByName(productNameFilter);
return View(model);
}
Here's my view
#model Ienumerable<Models.items.items>
#Html.DropDownList("productCategoryFilter",
new SelectList(ViewBag.CategoryDD),
"---Select Category---")
Side note - if you use a ViewModel between the View and the Model instead of binding directly to the model, you can put your SelectList on the ViewModel and use #Html.DropdownFor() instead of #Html.Dropdown(). The ViewBag should really be used sparingly.
However back to your original question:
What is "Items()"? in your line
var ddl = new Items();
I'm not sure what good reason you would have NOT to make it enumerable.
I suspect it is not working because you are making a selectlist from a select list twice --
in your code behind you are defining ViewBag.CategoryDD as a SelectList(), and then in your Razor code you are creating a new SelectList() from the existing selectlist. You shouldn't have to do this.
The way I would do this is create a ProductViewModel class that contains your product category list AND your list of products (your current model), and a property for the selected filter.
public class ProductViewModel
{
public IEnumerable<Model.items.items> ProductList {get;set;}
public IEnumerable<SelectListItem> ProductCategoryList {get;set;} //SelectList is an IEnumerable<SelectListItem>
public string SelectedCategory {get;set;}
}
Then on your view the model would be
#model ProductViewModel
#Html.DisplayFor(model => model.SelectedCategory, "---Select Category---")
#Html.DropdownListFor(model => model.SelectedCategory, Model.ProductCatgoryList)

Dynamically create random number of dropdownlists in MVC

I need to create a random number of dropdownlists in my view, based on the selected value of another dropdownlist. This is all done but my problem comes when I need to make the httppost because i never know how much data i need to save in my db.
In my model I have a list
public List<RoomToBooking> RoomsToBooking { get; set; }
that will get filled with x number of RoomToBooking when the Create view is rendered after the user makes a selction of dropdownlist 1:
var dogs = from d in db.Dogs
where d.Customer_ID == id
select d;
foreach (Dog item in dogs)
{
roomToBooking = new RoomToBooking();
roomToBooking.Customer_ID = id;
roomToBooking.Dog = item;
roomsToBookingList.Add(roomToBooking);
}
So I would like to create the same number of dropdownlist in my Create view
#Html.DropDownListFor(model => model.Booking.RoomToBooking, new SelectList(ViewBag.DeliveryTypes), new { #class = "selectbox" })
#Html.ValidationMessageFor(model => model.Booking.RoomToBooking)
So I in the end can be able to save it to my db
[HttpPost]
public ActionResult Create(EditBookingPensionViewModel model)
{
foreach (RoomToBooking item in objViewModel.RoomsToBooking)
{
//Save to db
}
}
I assume that I should use jquery to create the dropdownlists, but how do i create the dropdownlists so the selected values can be found in my viewmodel??
You may take a look at the following article. I slight adaption might be necessary for your scenario because you don't have add and remove buttons but instead you use the selected value of a dropdownlist to determine the number of dynamic rows to be added. But the concept is the exactly the same.

Dropdownlist value not getting set from SelectList passed to view in ViewData

I am trying to populate a dropdownlist of office locations(text) and addresses (value)
When viewing my page source in my browser after displaying the page I can see that the select (dropdownlist) option values are all "". Here is my code. I am using a LinqToSql data context call to get my data for the SelectList. In the debugger I can see that the list returned from my call does in fact have the addresses and office locations I need.
My model datacontext code:
public partial class uls_dbDataContext
{
public List<office_location> GetOfficeLocations()
{
return office_locations.ToList();
}
}
My controller code:
public ActionResult Directions()
{
uls_dbDataContext ulsdb_dc = new uls_dbDataContext();
ViewData["OfficeLocations"] = new SelectList(ulsdb_dc.GetOfficeLocations(),"location_address", "location_name");
ViewData["Title"] = "Directions";
return View();
}
My view code:
<%= Html.DropDownList("locations", (SelectList)ViewData["OfficeLocations"])%>
I had to upgrade to MVC RC2 from preview 4. It addressed drodownlist issues and fixed my problem.

Resources