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

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.

Related

Why .cshtml file don't see #model in .cshtml.cs file and i get Null References exception?

I've created an ASP.NET Core 6 MVC project, and I want to see "Test" when i request it but I'm getting NullReferenceException. But when I create the Razor pages application and try the same thing on that project, I don't get any errors.
I run app on Ubuntu 22.04, I use .NET Core 6.0 Framework.
namespace MyApp.Namespace
{
public class TestModel : PageModel
{
public string? Message { get; set; }
public void OnGet()
{
Message = "Test";
}
}
}
View:
#model MyApp.Namespace.TestModel
<dir>#Model.Message</dir>
Exception:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCoreGeneratedDocument.Views_Home_Test.ExecuteAsync() in Test.cshtml
#Model.Message
I tried to change namespaces and add a #page directive in Razor page. Nothing has changed.
According to the code above you should make the following declaration in the Razor view file:
#page
#using MyApp.Namespace
#model TestModel
<dir>#Model.Message</dir>
Detailed instructions on how to create a Razor Pages and #page, #model declarations you can find in the Microsoft documentation here: Razor Pages
MVC needs to pass model between View and controller. When you want to show values from backend, you need to return view with models.
create a model to pass data:
public class TestModel
{
public string? Message { get; set; }
}
set the default value in http get action:
public IActionResult Index()
{
TestModel test = new TestModel();
test.Message = "Test";
//return view with model
return View(test);
}
View
#model TestModel
<h1>#Model.Message</h1>
Now you can show Test in your view:

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
}

When rendering a view the model is not updated only the viewbag

So.... I have an action in my controller that basically copies the current model and returns a new view based on that copy. To inform the user that this is a copy I append a message via the viewbag stating that it's a copy. All seemed to be working until I noticed that it's not the copy that is being used when rendering the new view instead it's the original, but the viewbag on the other hand is updated so the message is shown.
Hmm, don't know if that's understandable so I'll try to show what i mean with some pseudo-code as well:
Model
public class Model{
[ScaffoldColumn(false)]
[HiddenInput(DisplayValue = false)]
public Guid Id { get; set; }
public string Name { get; set; }
}
View
<input type="submit" name="Copy" value="#_("Copy")"/>
Controller
public ActionResult Copy(model) {
ViewBag.Message = _("This is a copy.");
var clone = model.Clone();
return View("Index", clone);
}
I'm having a real hard time trying to wrap my head around this so any help/tips/pointers are really appreciated.
Oh, I've stepped through the code several times to ensure that the clone is really a clone. The only thing that differentiates them is the Id property and that is the new one in the controller but when the view renders it's back to the old one.
You need to clear the ModelState collection before returning the clone because the HtmlHelpers prefer to reuse the posted data:
public ActionResult Copy(model) {
ViewBag.Message = _("This is a copy.");
var clone = model.Clone();
ModelState.Clear();
return View("Index", clone);
}
You can read more about this feature in this artice: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes.

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);
}
}

ASP.NET MVC 3 _Layout.cshtml Controller

Can anyone help me with the subject? I'm using Razor view engine and I need to pass some data to _Layout. How can I do it?
As usual you start by creating a view model representing the data:
public class MyViewModel
{
public string SomeData { get; set; }
}
then a controller which will fetch the data from somewhere:
public class MyDataController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SomeData = "some data"
};
return PartialView(model);
}
}
then a corresponding view (~/Views/MyData/Index.cshtml) to represent the data:
#{
Layout = null;
}
<h2>#Model.SomeData</h2>
and finally inside your _Layout.cshtml include this data somewhere:
#Html.Action("index", "mydata")
You could use the ViewBag to pass data.
In your controller:
ViewBag.LayoutModel = myData;
Access in you layout:
#ViewBag.LayoutModel
It is a dynamic object, so you can use any property name you want.
The ViewBag method is the easiest. However if you need advanced and typed features, you can also try taking that part to a partial view (the part that'll render the dependent section) with a common controller (if the value can be calculated on it's own and doesn't need input from other controllers), and call RenderPartial on it from _Layout.
If you'd like I can give you some more info about it...

Resources