Asp.net Core MVC ModelMetadata.AdditionalValues add function - asp.net-core-mvc

I am upgrading MVC5 to Asp.Net Core 3 MVC and just found that ModelMetadata.AdditionalValues has been changed to IReadOnlyDictionary. We have stored information in additionalValues before. What is the alternative solution now?
Thanks in advance.
Wilson

What is the alternative solution now?
You could use ViewData and ViewBag to pass data to a view in ASP.NET Core.
ViewData
is a property of the Controller Base class, which returns a ViewDataDictionary object.
The ViewDataDictionary is a dictionary object which allows us to store key-value pairs. The key must be a case-insensitive string. To pass data to the view, you can assign values to the dictionary using the Key. You can store any number of items as needed in the ViewData.
The data stored in the ViewData object exists only during the current request. As soon as the view is generated and sent to the client, the Viewdata object is cleared.
The following is an example that sets values for a Title using ViewData in an action:
1. Codes in Controller
public IActionResult Index()
{
ViewData["Title"] = "Hello World!";
return View();
}
2. Codes in View
#ViewData["Greeting"]
ViewBag
isn't available in Razor Pages. ViewBag is a DynamicViewData object that provides dynamic access to the objects stored in ViewData. ViewBag can be more convenient to work with, since it doesn't require casting. The following example shows how to use ViewBag with the same result as using ViewData above:
1. Codes in Controller
public IActionResult SomeAction()
{
ViewBag.Greeting = "Hello";
return View();
}
2. Codes in View
#ViewBag.Greeting World!
Here you can find more information like below in this link.
ViewData attribute - Another approach that uses the ViewDataDictionary is ViewDataAttribute.
Using ViewData and ViewBag simultaneously
Summary of the differences between ViewData and ViewBag
When to use ViewData or ViewBag
Strongly typed data (ViewModel)

Related

In partial view: "The model item passed into the dictionary is of type"

I lack understanding of some basic MVC concepts, despite all my searching.
I created an MVC project in Visual Studio, which contains the partial view _LogOnPartial.shtml. I just want to access information within the view pertaining to the user, to put in a user dropdown menu. When I try to put this at the top of the partial view cshtml page I get the above error:
#model MyProject_MVC.Models.UserRepository
When I try this I also get an error:
#Html.Partial("_LogOnPartial", MyProject_MVC.Models.UserRepository)
'MyProject_MVC.Models.UserRepository' is a 'type', which is not valid in the given context
You have to provide an instance of MyProject_MVC.Models.UserRepository to the partial view. _LogOnPartial is strongly-typed to that type. It lets you access its public members at compile time and decide how you can display it in your view.
If you want to use your own type in that view, first you have to change the type that is strongly-typed to it.
#model MyProject_MVC.Models.UserRepository
Then you have to create an instance of that type in your action method and pass it to the view as the model or a property of the model.
public ActionResult LogOn()
{
return View(new UserRepository());
}
Now you can access this instance as Model object in your view.
#Html.Partial("_LogOnPartial", Model);
#model _LogOnPartial.Models.UserRepository should probably be: #model MyProject_MVC.Models.UserRepository
and for the last part, you have to provide and instance of the type UserRepository as the second parameter, not the type itself.

How to access objects inside a List, saved in a Session. ASP.NET MVC 3

So I have this code:
var list = new List<Carrito> {
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};
Session["list"] = list;
return View();
Then I load the view but I don't know how to print the the content that is inside the session. Any ideas?
This is the code I use inside the view but doesn't work:
#foreach(var item in (IEnumerable<object>)Session["list"] )
{
<p>#item.ProductId</p>
}
it's as simple as reading back the value from your session varable and cast it to the original type, then do whatever you want
example:
#{
if(Session["list"]!= null)
{
var listBackFromSession = (List<Carrito>)Session["list"];
// do what you want
}
}
My recommendation is to use the more elegant way of ViewBag.
a quote from official asp.net mvc website about Viewbag:
New "ViewBag" Property
MVC 2 controllers support a ViewData property that enables you to pass
data to a view template using a late-bound dictionary API. In MVC 3,
you can also use somewhat simpler syntax with the ViewBag property to
accomplish the same purpose. For example, instead of writing
ViewData["Message"]="text", you can write ViewBag.Message="text". You
do not need to define any strongly-typed classes to use the ViewBag
property. Because it is a dynamic property, you can instead just get
or set properties and it will resolve them dynamically at run time.
Internally, ViewBag properties are stored as name/value pairs in the
ViewData dictionary. (Note: in most pre-release versions of MVC 3, the
ViewBag property was named the ViewModel property.)
Further more, This is a good article to read about the different ways you have in MVC in order to preserve data: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
example:
var list = new List<Carrito> {
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};
// use ViewBag
ViewBag.myList = list;
then inside your view, read them back like this:
var myList = (List<Carrito>)ViewBag.myList;
// your code
You're doing MVC fundamentally wrong. In MVC, Views are there only to render a model. The logic of accessing that model should be implemented in controller, or in any other place, but not in the View itself.
Thus I recommend that you simply pass your list to the view, and make your view strongly-typed by including #model List<Carrito> at the top.

How can i supply value to Textbox generate from #Html.EditorFor in MVC razor?

I am just new to MVC.
when we use "#Html.EditorFor" in razor view, it generates textbox.
My requirement is that I need to supply some value from viewbag or session to user's in that textbox?
Is it possible and if yes how can i do?
OR
What are the alternatives?
In your action method in the controller, pre-load a model with some data:
public ActionResult Index()
{
MyModel model = new MyModel();
model.FirstName = "Bob";
model.LastName = "Hoskins";
return View(model);
}
Then make your View strongly typed. These pre-set values should now appear on your view. You probably want to populate them from a service layer or resource file, rather than have them as hardcoded strings like my example.

How do I pass an object from the Index view to the edit view using MVC3

I have created a simple WCF service that is to be configured by an MVC3 UI.
When I call the index page from my controller, I want to display the values held in the configuration, which has been returned by the service. The user could then chose to edit these settings and then send them back to the service.
I want to do something like this in the index view ...
<div>
#Html.ActionLink("Edit", "Edit", model)
</div>
and then consume the model in the controller like this...
[HttpPost]
public ActionResult Edit( SettingsModel Config)
{
try
{
List<string> configErrors = null;
if (ModelState.IsValid)
{
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel = new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl)))
{
IChangeService channel = serviceChannel.CreateChannel();
configErrors = channel.SetSysConfig(Config);
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
but this doesn't work.
Any suggestions???
When the form gets posted, all the input type fields data is collected and sent to the server. You can see this data using FireBug. The key point here is that, is the data that is being posted in a form, that MVC's default model binder can understand and map it to the model object, which is being passed as input parameter to the action method.
In your case, the model is of type "SettingsModel". You have to ensure that, the form data that is being posted is in format, that can be mapped to the "SettingsModel" object.
Same kind of question discussed in another thread : Can't figure out why model is null on postback?
Check Out this article : NerdDinner Step 6: ViewData and ViewModel
In the above article, carefully go through the "Using a ViewModel Pattern" section. My guess is that, this is what you are looking for.
You will need to post the values to populate the SettingsModel object on the Edit action. You can do this using hidden form fields if you don't want the user to see it. Otherwise you could have no parameters on the Edit action and make another call to the web service to populate the Settings model.

controller action returning View(tuple) asp.net mvc 3

Is there a way for the controller to pass a tuple as a model to the View?
Something like this:
return View(Tuple<LandingPage, Models.FilterModel>(landingPage, filter));
Thank you
Yes, you just need to instantiate the Tuple:
return View(new Tuple<LandingPage, Models.FilterModel>(landingPage, filter));
Although you're probably better off creating a composite view model type which contains properties for the landing page and the filter model.

Resources