How can i supply value to Textbox generate from #Html.EditorFor in MVC razor? - asp.net-mvc-3

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.

Related

Asp.net Core MVC ModelMetadata.AdditionalValues add function

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)

.NET MVC3/Holding temp model

I have a situation where i have to take input(form) from user. After continue button is pressed next view page is displayed. But after continue is pressed i don't want to store the model in the DB. I have to display some details(combining some tables) according to input given by the user earlier and again get some data from user. Only then i want to store the model in the respective tables.
How can i perform this? I tried getting Model from user and passing to the function that generates next page. Is this is way to do it? or there is other way around?
Store the model submitted by the first form in session.
[HttpPost]
public ActionResult ContinueForm1(Model1 model1)
{
if(ModelState.IsValid)
{
Session["Model1"] = model1;
return View("Form2");
}
return View();
}
[HttpPost]
public ActionResult ContinueForm2(Model2 model2)
{
if(ModelState.IsValid)
{
... model2 is already here, get the model1 from session
... and save to datatbase finally return a different view or redirect to some
... other action
}
return View();
}
You are heading down the right track.
You need to grab the model that is passed back from the first view - preferably you are using ViewModels here rather than binding directly to your db models. Have a look at http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/ and Why should I use view models? as to why these are good things.
The easiest way to do this is to pass the model in as an argument to your method e.g.
Assuming that your views are using the same ViewModel ( which may or may not be true) then you can send the viewmodel straight to your new view - else you can copy the elements into a new viewModel and send that.
e.g.
[HttpPost]
public ViewResult Step1(MyViewModel viewModel)
{
//Do some validation here perhaps
MySecondViewModel secondViewModel = new MySecondViewModel{
Id = viewModel.Id,
// etc. etc.
};
return View("Step2", secondViewModel);
}
Then you can carry on as you need until you have to persist the entity to the database.
NB as you do not need to do anything special in the form to make it post the model as an argument as long as the view is strongly typed to that ViewModel.

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 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.

prepopulate Html.TextBoxFor in asp.net mvc 3

I'n new at this, so apologies if this isn't explanatory enough. I want to prepopulate a field in a form in asp.net mvc 3. This works;
#Html.TextBox("CompName", null, new { #value = ViewBag.CompName })
But when I want to prepopulate it with a value and send that value to my model, like this;
#Html.TextBoxFor(model => model.Comps.CompName, null, new { #value = ViewBag.CompName })
It won't work. Any ideas?
Thanks in advance!
So, I would suggest is to move to using viewmodels rather than the ViewBag. I made a folder in my project called ViewModels and then under there make some subfolders as appropriate where I put my various viewmodels.
If you create a viewmodel class like so:
public class MyViewModel
{
public string CompName { get; set; }
}
then in your controller action you can create one of those and populate it, maybe from some existing model pulled from a database. By setting that CompName property in the viewmodel, it'll have that value in your view. And then your view can look something like this:
#model MyNamespace.ViewModels.MyViewModel
#Html.EditorFor(model => model.CompName)
or #Html.TextBoxFor would work too.
Then back in your controller action on the post, you've got something like this:
[HttpPost]
public ActionResult MyAction(MyViewModel viewModel)
{
...
// do whatever you want with viewModel.CompName here, like persist it back
// to the DB
...
}
Might be that you use something like automapper to map your models and viewmodels but you could certainly do that manually as well, though the whole lefthand/righthand thing gets quite tedious.
Makes things much easier if you do it this way and isn't much work at all.
Update
But, if you really want to pass that value in view the ViewBag, you could do this:
In your controller action:
ViewBag.CompName = "Some Name";
Then in your view:
#Html.TextBoxFor(model =>model.Comps.CompName, new {#Value = ViewBag.CompName})
And that'll pre-populate the textbox with "Some Name".
I'd still go with the viewmodel approach, but this seems to work well enough. Hope that helps!
From your controller, if you pass a model initialized with default values using one of the View(...) method overloads that accepts a model object, these values will be used by the view when rendered. You won't need to use the #value = ... syntax.

Resources