Pass data between Views in MVC - c#

I'm working on a Web Application project using C# and MVC that will take in two URLs in a form and use them to create an instance of a class I have created called "ImageSwap." This model has some data (a username of the person performing the swap; two variables which hold the URLs of two images to be swapped; two variables which save the actual names of these files without all of the rest of the URL information; and two arrays which represent the file locations to check for these files). Right now, I have it so that the initial index view creates the instance of the class and passes it to the same view with the information put in through the form, submitted via POST, like so:
public ActionResult Index()
{
Ops.Operations.Models.ImageSwapModel newImageSwap = new Models.ImageSwapModel();
return View(newImageSwap);
}
[HttpPost]
public ActionResult Index(ImageSwapModel imageSwap)
{
var oldFileFound = false;
var newFileFound = false;
if (ModelState.IsValid)
{
//Perform data manipulation and set needed values
}
}
It then performs some functions on the data, such as parsing out the filename at the end of the URL, and a directory number (which is the first part of this filename, i.e. directory#_fileName.jpg). All of this works fine.
My problem is that I would like to pass this model to another view once it has data populated in all of its fields by this initial ActionResult so that I can have a verification view, which would allow the user to preview the two files side by side so that they can ensure they are swapping the appropriate images. They should then be able to hit another submit button which will initiate the actual moving/replacing of the images and be taken to a page confirming.
Is there a way to pass data from this controller to a different view? My confusion arises because I cannot create another version of an ActionResult of Index with the same input, but I do not want to have the actual swapping of the images occur without a preview and a prompt. Should I re-write my Index view so that it utilizes partial views in order to accomplish this? What is the easiest way to have data persist through multiple steps and views?

What is the easiest way to have data persist through multiple steps
and views?
Your question sounds like you're trying to achieve what you can easily do with sessions. The session object allows you to persist data between requests simply by adding it to the Session object on the HttpContext that exists within the base class that your controller extends, like so:
(Note the Serializable attribute. This allows your object to be serialized into the session object).
[Serializable]
public class ImageSwapModel {
// Your class's properties
}
Then in your controller you can do the following:
[HttpPost]
public ActionResult Index(ImageSwapModel imageSwap)
{
var oldFileFound = false;
var newFileFound = false;
if (ModelState.IsValid)
{
this.HttpContext.Session["ImageSwap"] = imageSwap;
}
}
When you want to retrieve the model you can grab it from the session like so:
var imageSwap = (ImageSwapModel)this.HttpContext.Session["ImageSwap"];
Taking it one step further:
Whilst the above will work fine, generally it's not a good practice to reference the HttpContext object directly in your code as it creates unnecessary coupling to the HttpContext object that can easily be avoided. Instead you should opt to inject an instance of the session object via Dependency Injection. Here is a similar answer that provides a basic idea as to how you can do this.

You can return different views with Models being passed to them in your one Index action like
if(some condition)
{
Return View("ViewVersion1", MyModelVersion1);
}
else
{
Return View("ViewVersion2", MyModelVersion2);
}

Related

asp.net mvc ViewState implementation

I working on a web project where I first get data from the database and bind to the Html control. If there is a validation error I will send the same view back for rendering with the displayed validation errors. When the page comes up, there is an exception. I stepped through the code and found that the model was passed will null collection. Basically any property that was not binded to a textbox was changed to null. I was told not to use session or viewdata to keep temp storage. So I call a method SaveViewState where it save all the property value of the ViewModel property to a static variable like so
private static MyViewModel _viewModel;
private MyViewModel SaveViewModel(MyViewModel viewModel)
{
if (_viewModel == null)
{
_viewModel = new MyViewModel ();
}
if (!string.IsNullOrEmpty(viewModel.MyName))
_viewModel.MyName= viewModel.MyName;
if (!string.IsNullOrEmpty(viewModel.Number))
_viewModel.Number= viewModel.Number;
if (!string.IsNullOrEmpty(viewModel.Address))
_viewModel.Address= viewModel.Address;
if (!string.IsNullOrEmpty(viewModel.State))
_viewModel.State= viewModel.State;
}
It works but I think it is very inefficient and there must be a better way to implement ViewState in MVC with Session or ViewData or HiddenFields? By the way, I was told not to use those three.
Any help is appreciated. Thanks.
I am not sure if this solution is worse than using a session or hidden fields. In your action you should return the corresponding view with the same model that was posted. The ActionResult should be something like this:
public ActionResult SomePost(SomeModel model)
{
if (!ModelState.IsValid())
{
//error in validation
return View(model);
}
//post save redirect and stuff
return ... redirect?
}
The ModelState.IsValid() will test according to the DataAnnotations. Standard attributes like [Required], [MaxLength] etc. are available.
In this configuration, the use of a SaveViewModel function is not required. If your collection is null after post: re-query it, post it or fetch it from a ViewData like object.
There are good reasons not to use those three you mentioned, but if you know that reason you might want to consider it:
1) Use of session: will make scalability difficult because every request in a session must hit that specific server.
2) Hidden fields: Not really a problem IFF you realize the hidden field can be manipulated in a browser. So don't store ID's there
3) ViewData: basically breaks the MVC pattern; you can use it to store data but that's what a model is for. It totally legitimate to use ViewData from a filter. To provide some general functionality for example.

Keep data in ViewModel when validating in MVC5

In my asp.NET MVC5 app I have a controller that supplies a view which is strongly typed vs a viewmodel. This viewmodel has a SelectList property (among others), and the controller supplies the data on creation from the database:
public ActionResult Simulation() {
var SimVM = new SimulationVM(
StrategyRepository.GetStrategies().Select(n => n.Name),
);
return View(SimVM);
}
The SelectList is then used as data source for a DropDown choice in a form. The HttpPost method does some datavalidation, i.e.,
[HttpPost]
public ActionResult Simulation(SimulationVM _simVM) {
if (ModelState.IsValid) {
// ...
}
else return View(_simVM);
}
So with the code above, the DropDown data is empty, since on posting, the SimulationVM object is created new. The usual trick of using Html.HiddenFor does not work on collections.
Of course, I could go back and fetch the data again from the database, but that seems to be bad, a database fetch for such a simple thing as a validation where I know the data hasn't changed.
What is the best (or for the sake of not being subjective: any) way to keep some data in the ViewModel (or repopulate it efficiently)?
If it is a requrement that you not go back to the database and you're 100% confident that the data will not change (i.e. this is a list of states as opposed to a list of orders or something) then you can add the collection to a session variable. Here's a link to a decent article:
https://code.msdn.microsoft.com/How-to-create-and-access-447ada98
That being said, I usually just go to the database and get the data again. If doing so for a second time is causing huge performance issues, it is most likely causing performance issues the first time and you should treat the problem rather than the symptom.

Passing model through a page to another page

We have a job application that uses a two step process. I need to tweak this slightly. The easiest way I can see doing this is removing the application creation stage from step one, and just passing it to step two which is a separate view.
Page 1 - Step 1
public ActionResult Apply(JobApplicant jobapp, string HiddenJobId)
{
jobapp.JobID = Convert.ToInt32(HiddenJobId);
//JobsHelper.CreateJobApplicant(jobapp);
return View("ApplyResume", jobapp);
}
The above code used to CreateJopApplication(). I commented this out and am now passing this to the next step/page.
However once on this new page I then have an [HttpPost] that takes that jobapp but at this point it is all null.
The jobapp(JobApplication) is about 140 columns, I'd hate to have to create a hidden text field for all of that. Is there an easier way to pass a model across two pages?
Step 2 - Page 2
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string applicantId, string coverLetter, JobApplicant jobapp)
{
// jobapp is null during this entire step, passed in null its as if the page before never had it.
JobsHelper.CreateJobApplicant(jobapp);
.......
You may be able to use TempData. It is like a session state but it's removed once it gets used. It is good for one round trip.
With a stateless framework like MVC, you can:
Persist inside the form using hidden fields
Persist in database
Persist in session state or temporary state

Is using TempData to pass details between controller actions bad practice?

I have certain situations where I need to pass a value between controller actions.
When passing a returnUrl from a view to all nested views. In the
view I have
#{
TempData["returnURL"] = Request.Url.AbsoluteUri;
}
and then access it in a similar way to this (in my real version I
check that the key is in TempData and that the returnURL is a real
URL):
return Redirect(TempData["returnURL"].ToString());
If it needs to continue on past the first page change (i.e. Search
page -> Edit page -> Edit Section page) I'm adding it again
TempData["returnURL"] = TempData["returnURL"];
When I need to pass a value from one controller action through a
view to another controller action that is called by ajax such as
here:
public ViewResult Index(FormCollection form)
{
var model = new GridColumnChooserViewModel();
//Select deleted/not deleted rows
if (form.HasKeys())
model.ShowRows = (form["deletedDropDown"] == null) ?
"Active" :
GetOptionByName(form["deletedDropDown"]);
TempData["ShowRows"] = model.ShowRows;
...
}
and then in my other ajax-called action controller I access it:
public JsonResult GetData()
{
//Select deleted/not deleted rows
var showRows = (TempData.ContainsKey("ShowRows") && TempData["ShowRows"] == null) ?
"Active" :
GetOptionByName(TempData["ShowRows"].ToString());
//refresh tempdata showrows so it is there for next call
TempData["ShowRows"] = model.ShowRows;
return this.GetDataSource(showRows);
}
My question is, is this really bad practice? From my understanding of it, I'm essentially using TempData like a session cookie. Is there a better way to do this, like using an actual cookie?
Yes, I would say that this in general is bad practice. While the ViewData dictionary approach is fast and fairly easy to implement it can leads to typo's and errors that are not caught at compile time. An alternative would be to use the ViewModel pattern which allows you to use strongly-typed classes for the specific view you need to expose values or content within. Ultimately giving you type safe and compile time checking along with intellisense.
My first choice would be to use a view model. If that doesn't fit then using session state may be just fine.
It seems like you are using TempData to flow state through the various pages of your site; in general, I'd say this is a bad practice.
Ideally, you would flow whatever upcoming state you would need to the client, and the client would store it (in some sort of JSON or whatever). Then, the client would return it to you as part of their action, and then you'd pass back the appropriate state, etc.; it speaks more to the stateless nature of HTTP applications.
I changed both situations to use Session so that I didn't have to keep pushing the TempData value on.
public ActionResult Create()
{
Session["returnURL"] = Request.UrlReferrer.AbsoluteUri;
...
}
Then I access it like this
var returnURL = (Session["returnURL"] != null) ? Session["returnURL"].ToString()
: Url.Action("Index", "Home");
Seems a bit better.

Preparing models for ASP.NET MVC views

When returning strongly typed models for views such as Create and Edit (when validation of the object we are editing fails) I usually prepare the models like this:
//
// GET: /Invoice/Create
public virtual ActionResult Create()
{
// prepare the empty model
Invoice model = new Invoice();
model.Client = new Client();
model.Client.PostCode = new PostCode();
return View(model);
}
//
// POST: /Invoice/Create
[HttpPost]
public virtual ActionResult Create(Invoice document,
FormCollection collection)
{
// check for errors
if (!ViewData.ModelState.IsValid)
{
document.Client = new Client();
document.Client.PostCode = new PostCode();
return View(document);
}
Now I know that this is how others do it too, in fact you can see this same approach in MVC Music Store sample and others. However, this is very error prone because one might accidentally left out a referenced entity which is required in the view. It also requires too much thinking about view/model interaction. What I would want is some sort of automatism. Value typed properties in models usually aren't the problem because they default either to zero or empty strings. Reference types however should be initialized with new..but sooner or later we end up with code blocks that are being repeated, reference type properties being left out, etc..And I don't think it's good coding practice either.
What are other options we could take?
UPDATE:
Because replies kinda missed the point (they do not relief us of thinking about models in any way and require additional code in model classes), I was thinking if this option would work:
Use custom Action filter,
override OnActionExecuted()
use Reflection inside this method to take out the object from the Model and enumerate its public properties and try to initialize them.
I have steps 1, 2 and 3 partially implemented but I cannot figure out how to do "... = new Client();" programatically with Reflection.
Make the properties of your model return a new instance if it is null
private Client client;
public Client Client
{
get
{
if (client == null)
client = new Client();
return client;
}
}
I suggest that you use a Strongly typed view bound to a ViewModel that is distinct from the Domain Model you're trying to create, and put whatever necessary logic into the constructor of the ViewModel
I'm not sure I fully understand your question. You want what automated? ViewModels and Views? Are you creating strongly typed views?
I have created a T4 template that I point to a database and it generates a ViewModel for every table. Foreign keys become drop down lists, long strings get a TextArea instead of TextBox, etc. I then delete the ones I don't need and modify the ones I want to keep. It's not a totally automated process, but it does 80 to 90 percent of the work, depending upon the project.
Then I generate strongly typed Views from those ViewModels.
It also sounds like you might be interested in AutoMapper.

Categories

Resources