MVC Separation of Concerns - asp.net-mvc-3

so I was going on creating my MVC 3 web app when it dawned on me that I might be putting entirely too much logic in my Controller, that it needs to be in the Model instead. The problem with this is, that in this particular instance I'm dealing with a file.
The SQL database table stores the path of the file, and the file itself is saved in a directory. So in the database, the file path is stored as an nvarchar, and in the model, the file is a string, everything's consistent to that point. The issue comes when it's time to upload the file, at that point I'm dealing with a System.IO.File.
So the question is, how do you provide System.IO.File logic inside the model for the file when in the back-end it is actually a string?
I had finished the functional version of the Controller and had some logic already in it, and was about to add more when I realized that I was working against the system. What I mean is that in order to have server-side validation, the logic needs to be in the Model in order for the input validation to behave and work according to proper MVC rules, obviously optionally using client-side validation in conjunction.
Currently...
Here is my View:
#model ProDevPortMVC3.Profile
#{
ViewBag.Title = "Profile Photo Upload";
}
<h2>Photo Upload</h2>
<img alt="Profile Image" src="#Html.DisplayFor(model => model.ProfilePhotoPath)" />
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("UploadPhoto", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<br />
<input type="file" name="File1" />
#Html.ValidationMessageFor(model => model.ProfilePhotoPath)
<input type="submit" value="Upload" />
}
Here is my Controller (just the relevant action method):
[HttpPost]
public ActionResult UploadPhoto(int id, FormCollection form)
{
Profile profile = db.Profiles.Find(id);
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
try
{
string newFile = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/Content/users/" + User.Identity.Name + "/" + newFile));
profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile;
UpdateModel(profile);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
And here is my Model (just the part relevant to the file):
public string ProfilePhotoPath { get; set; }
So I guess, what are your guys' solutions in these particular situations?

Description
Assuming i understand your question. I have read your question a few times. ;) If i don't understand, please comment my answer in order to get a better answer (i will update)
I think that you want is.. How to Model Validation for your particular case.
You can add Model Validation errors using the ModelState.AddModelError("Key", "Message) method.
ModelState.AddModelError Adds a model error to the errors collection for the model-state dictionary.
Sample
ModelState.AddModelError("ProfilePhotoName", "YourMessage");
This will affect ModelState.IsValid
So you can do whatever you want (your logic) and can make your Model invalid.
More Information
MSDN - ModelStateDictionary.AddModelError Method

There are any number of answers to this question. I'll take a crack at it knowing the risk going in due to varying opinion. In my personal experience with MVC3 I like to use flatter, simpler Models. If there is validation that can be done easily in a few lines of code that doesn't require external dependencies then I'll do those in the Model. I don't feel like your System.IO logic is validation, per se. Validation that could go in the Model, in my mind, is whether the filename is zero length or not. The logic to save is something you can put in your controller. Better yet, you could inject that logic using the Inversion of Controller pattern and specifically a Dependency Injection solution.

Related

Why is my textBoxFor using my route data?

So I have these three lines:
<div style="background-color: lightgreen;">#Html.TextBoxFor(m => m.Id)</div>
<div style="background-color: green;">#Html.DisplayTextFor(m => m.Id)</div>
<div style="background-color: pink;">#Model.Id</div>
I've identified that the lightgreen value is not my Model.Id but the Id that is set by my route:
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "MyFunController", action = "Index", id = UrlParameter.Optional });
I've come accross some explanations here:
http://forums.asp.net/t/1792086.aspx/1
http://www.hanselman.com/blog/TheWeeklySourceCode38ASPNETMVCBetaObscurityModelStateIsValidIsFalseBecauseModelBinderPullsValuesFromRouteData.aspx
http://ayende.com/blog/3683/reproducing-a-bug
But they have all left me on my appetite. I'm looking for a smart way to work around this, I don't want to change my model's property names nor do I want to change the name of the route item. If I do it will represent a lot of work for me and is not ideal.
I'm sure I'm not the only one with this issue?
(This is MVC 4)
Thanks!
You could remove the problematic value from the ModelState (which is where the Html helpers are taking it from) in the controller action that is rendering the view:
public ActionResult SomeAction(int id)
{
ModelState.Remove("Id");
MyViewModel model = ...
return View(model);
}
Now it's the Id property of your view model that's gonna get used by the TextBox and not the one coming from the route.
Obviously that's only an ugly horrible workaround. The correct way is to of course properly define your view models so that you do not have such naming collisions.

Manually validate textbox with jQuery unobtrusive validation asp.net MVC3

So I have a multi-step process that allows a user to retrieve a forgotten password. The steps are like so, with a different action for each step in my controller:
Enter username and email
Enter password question answer
Email a recovery link to the user if all goes well
I tried using one model for everything:
public class AccountForgotPassword
{
[Required()]
[DisplayName("Username")]
public string UserName { get; set; }
[Required()]
public string Email { get; set; }
[Required()]
public string PasswordAnswer { get; set; }
}
But when I check ModelState.IsValid on the first action, since the user can't input their password answer question yet, it will always be false and makes for some interesting code to check that the model state is in fact valid but is only missing the password answer since I don't know who the user is yet.
To get around this, I decided to forgo a typed model and just use string parameters in my actions. Only problem now is that I can no longer use the easy validation wire-ups you get with model binding.
With that said, does anyone know an easy way to manually wire-up the jQuery validation to individual inputs so it will check the required rule? Also, will this wiring allow me to use the default error messages the validator generates, or will I have to supply my own upon wiring them up? Would it be this easy in my view:
#{
ViewBag.Title = "Forgot Password";
}
<h2>
Forgot Password</h2>
#using (Html.BeginForm())
{
<p>
#Html.Label("UserName", "Username")
#Html.TextBox("UserName")
#Html.ValidationMessage("UserName")
</p>
<p>
#Html.Label("Email", "Email")
#Html.TextBox("Email")
#Html.ValidationMessage("Email")
</p>
<p>
<input type="submit" value="Send Form" />
</p>
}
<script type="text/javascript">
$.validator.unobtrusive.addRule(..something here...);
</script>
Also if there is a better way to do this, please let me know.
UPDATE
For anyone else that finds this, I did figure out how to add the rules manually. Should have just read the validation docs first. Assuming the view html above, the script would be:
<script type="text/javascript">
$(function () {
$('#UserName').rules('add', {
required: true,
messages: {
required: 'The username field is required.'
}
});
$('#Email').rules('add', {
required: true,
messages: {
required: 'The email field is required.'
}
});
$.validator.unobtrusive.parse('form');
});
</script>
However, after thinking about it some more and taking AFinkelstein's answer into account, I think I will just go ahead and make 2 different view models and let the framework do the work for me.
If you validate just the username and password first, and then the Password answer second, I think the easiest solution is to have two separate View Models. Then you can still use the appropriate View Model and validation for each section.

How to pass both model value & text value to controller in mvc?

I want to pass two values from view to controller . i.e., #Model.idText and value from textbox. here is my code:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Model.idText
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
}
But problem is if i use "Url.ActionLink() i can get #Model.idText . By post action i can get textbox value using FormCollection . But i need to get both of this value either post or ActionLink
using ajax you can achieve this :
don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hope this will be helpful.
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.Hidden("idText", Model.idText)
#Html.TextBox("textValue")
<input type="submit" value="Submit"/>
}
In your controller
public ActionResult SaveData(String idText, String textValue)
{
return null;
}
I'm not sure which part you are struggling with - submitting multiple values to your controller, or getting model binding to work so that values that you have submitted appear as parameters to your action. If you give more details on what you want to achieve I'll amend my answer accordingly.
You could use a hidden field in your form - e.g.
#Html.Hidden("idText", Model.idText)
Create a rule in global.asax and than compile your your with params using
#Html.ActionLink("My text", Action, Controller, new { id = Model.IdText, text =Model.TextValue})
Be sure to encode the textvalue, because it may contains invalid chars
Essentially, you want to engage the ModelBinder to do this for you. To do that, you need to write your action in your controller with parameters that match the data you want to pass to it. So, to start with, Iridio's suggestion is correct, although not the full story. Your view should look like:
#using HTML.BeginForm("SaveData","Profile",FormMethod.Post)
{
#Html.ActionLink("My text", MyOtherAction, MaybeMyOtherController, new { id = Model.IdText}) // along the lines of dommer's suggestion...
<input type="text" name="textValue"/>
<input type="submit" name="btnSubmit"/>
#Html.Hidden("idText", Model.idText)
}
Note that I have added the #Html.Hidden helper to add a hidden input field for that value into your field. That way, the model binder will be able to find this datum. Note that the Html.Hidden helper is placed WITHIN your form, so that this data will posted to the server when the submit button is clicked.
Also note that I have added dommer's suggestion for the action link and replaced your code. From your question it is hard to see if this is how you are thinking of passing the data to the controller, or if this is simply another bit of functionality in your code. You could do this either way: have a form, or just have the actionlink. What doesn't make sense is to do it both ways, unless the action link is intended to go somewhere else...??! Always good to help us help you by being explicit in your question and samples. Where I think dommer's answer is wrong is that you haven't stated that TextValue is passed to the view as part of the Model. It would seem that what you want is that TextValue is entered by the user into the view, as opposed to being passed in with the model. Unlike idText that IS passed in with the Model.
Anyway, now, you need to set up the other end, ie, give your action the necessary
[HttpPost]
public ActionResult SaveData(int idText, string textValue) // assuming idText is an int
{
// whatever you have to do, whatever you have to return...
}
#dommer doesn't seem to have read your code. However, his suggestion for using the Html.ActionLink helper to create the link in your code is a good one. You should use that, not the code you have.
Recapping:
As you are using a form, you are going to use that form to POST the user's input to the server. To get the idText value that is passed into the View with the Model, you need to use the Html.Hidden htmlhelper. This must go within the form, so that it is also POSTed to the server.
To wire the form post to your action method, you need to give your action parameters that the ModelBinder can match to the values POSTed by the form. You do this by using the datatype of each parameter and a matching name.
You could also have a complex type, eg, public class MyTextClass, that has two public properties:
public class MyTextClass
{
public int idText{get;set}
public string TextValue{get;set;}
}
And then in your controller action you could have:
public ActionResult SaveData(MyTextClass myText)
{
// do whatever
}
The model binder will now be able to match up the posted values to the public properties of myText and all will be well in Denmark.
HTH.
PS: You also need to read a decent book on MVC. It seems you are flying a bit blind.
Another nit pick would be to question the name of your action, SaveData. That sounds more like a repository method. When naming your actions, think like a user: she has simply filled in a form, she has no concept of saving data. So the action should be Create, or Edit, or InformationRequest, or something more illustrative. Save Data says NOTHING about what data is being saved. it could be credit card details, or the users name and telephone...

ASP.NET MVC Routes and Client Specifc Functions

I'm working on an application where a system is being built where multiple "customers" will use the system and 99.9% of the controllers/actions will be the same, just pulling different data, but there are times and places where a custom controller action, or view might be needed.
Right now I'm using a default route similar to the following to get the company name with requests.
routes.MapRoute(
"Default", // Route name
"{company}/{controller}/{action}/{id}",
new {company = "Unknown", controller = "Home",
action = "Index", id = UrlParameter.Optional}
);
This works great as I can have my individual controller actions defined like this
public ActionResult ShowReport(string company)
{
//Actual code goes here..
}
I have a system in place that will get the data segment for this specific company and return the proper view. SO for my 99.9% situation this looks great. What I'm looking for is a solution for when I need to render a different view, or have additional actions that are specific to one company.
I could add in switch or other logic within my action, but that feels overly dirty...
For a specific company you can use something like this and put it before the default action, in this case url has to contain Company1/somethingcontroller/etc/etc.
routes.MapRoute(
"Company1Default", // Route name
"Company1/{controller}/{action}/{id}",
new {company = "Company1", controller = "DefaultControllerForCompany1",
action = "Index", id = UrlParameter.Optional}
);
While I actually lean to Jay's answer pertaining to the use of data within models, I think that there is another option. Be warned that I haven't played this all the way out and don't have a full understanding of your application...
Why would you want to hardcode a company name within your global.asax? I don't think that it would be very scalable. If you want to add support for an additional 10 companies, you'd have to create 10 new entries. Also, what if you want to change the name of a company because of a buyout or something? More maintenance.
Why not add a route to send every company to the same controller like...
routes.MapRoute(
"CompanyRouting", // Route name
"{companyname}/{action}",
new { controller = "MySingleCompanyControllerName", action = "Index", companyname = UrlParameter.Optional }
);
MySingleCompanyController.cs
Once in your controller you can just get whatever the companyname value is whenever you want it.
public ActionResult Index()
{
ViewData["companynamevalue"] = RouteData.Values["companyname"];
return View();
}
Index.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
Requested Company Name = <%: ViewData["companynamevalue"] %>
</div>
</body>
</html>
NOTE: One more thing to look into for routing help is Phil Haack's routing debugger.
Defining which view is return from an action is easy:
return View("Index");
This will return the view named "Index" no matter which action is invoked.
On the other hand, both views and actions must be defined at compile time, so you cannot dynamically create them (from what i know of).
I might suggest implementing the Command Pattern in your action to get exactly what you would want for individual companies from a single action.

Passing values between View and Controller in MVC 2

I'm constantly confused about how to pass values between Views and Controllers in MVC. I know I can set ViewData in the Controller and use that in the View, but what about the other way around?
What I have found is I can use a hidden field and then access it through Request.Form["name"] like this:
<% using (Html.BeginForm("Upload", "Customers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<br />
<input id="currentDir" type="hidden" name="currentDir" value="" />
<input type="file" name="fileTextbox" id="fileTextbox" />
<br />
<br />
<input type="submit" value="Send" />
<% } %>
What complicates it even more is that the value originally comes from a jquery script, so that's why the input field was the only way I could think of. But it still feels wrong... Maybe it isn't but I'd basically like to know if there are other more "proper" established ways to pass values between the View and Controller (both ways). Should one use querystrings instead? If so, how would they look in the html.beginform htmlhelper?
Also, what I'm trying to do here is enable upload possibilities for my application. And I'm trying to make the whole application as "Ajaxy" as possible. But this form will make a complete post. Is there another way to do this and not have to reload the entire page for this upload?
Let's ignore the "AJAX-y" aspects for a moment (because that's a different issue) and just look at passing data between views and controllers. I would first recommend that you check out the NerdDinner Tutorial which provides some good insights into how MVC works and how you use some of the features of MVC.
To address your specific question of how data is passed from View to Controller and back, there are a few ways to do this. However, the one that tends to make sense to most people is the idea of using strongly-typed views.
Let's say you have a model called Person. For now, don't worry about how we store Person data - we just have a Person class in the Models folder inside your MVC project.
public class Person {
public string FirstName;
public string LastName;
public Person() {
FirstName = "John";
LastName = "Doe";
}
}
When we want to display data about Person in a View, we make a request to a specific controller. In this case (and for clarity) we'll call this controller the MainController. This will go in the Controllers folder and will be called MainController. Let's call the Action (an action is really just a specialized method) we want to get data from Index. Due to how ASP.NET MVC routing works, the path to our server will be: http://localhost/Main/Index. Notice the Controller (minus the "Controller" name), and the Action make up the path. (The first part is your server name, of course.)
Let's look at your controller - I'm going to keep it very simple for now:
public class MainController : Controller {
public ActionResult Index() {
Person person = new Person();
return View(person);
}
}
What we have going on inside the Index Action is that it is returning a View (which, by default, has the same name as the Action) and a model to correspond with that view. Now, we have to create our view.
The important part here is that you want to strongly-type the model that is being returned in the controller to your view. You do that with this line (which is first in your aspx file).
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewUserControl<Project.Namespace.Person>" %>
Notice the "Inherits" attribute and notice that your Person model makes up that attribute.
Now, just code the rest of your view as normal. Let's say we want to display the current Person name, and allow someone to change the name. The page would look like this (I'm not making this pretty):
<% using (Html.BeginForm()) { %>
<%: Html.LabelFor(model => model.FirstName) %>
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.LabelFor(model => model.LastName) %>
<%: Html.TextBoxFor(model => model.LastName) %>
<input type="submit" value="Submit" name="submitButton" />
<% } %>
This is the important part about getting data back and forth between Controllers and Views. What we are doing here is that we are taking your strongly-typed view (which is typed with the Person class) and using helper methods (like LabelFor and TextBoxFor) to tie the model together with its data and, ultimately, together with the actions contained in the controller (which we have to finish developing here in one moment).
So, you can now see the data. But, if a user changes the name and clicks submit - we want the page to display the new name. This means we need to add one more action to MainController - the one that receives the data.
[HttpPost]
public ActionResult Index(Person person) {
// Do whatever you want with the Person model. Update a database, or whatever.
return View(person);
}
This action looks very similar to the other action we just developed. However, this one takes a person object (from the form that is being submitted) and it gives the controller an opportunity to do whatever needs to be done with that object. Once this is done, you can choose to redirect to a different page, redisplay the page (useful if there are errors), or do any number of other things.
Again, this is ALL covered (and much more) in the NerdDinner Tutorial. I highly recommend you read and follow through that.
As for the AJAX-y aspects you discussed, the premise is still the same (although there is a little bit of JavaScript/jQuery work that goes on in there). I won't go into it now, but the basics are also covered in the NerdDinner tutorial.
I hope this gets you started. I remember being a bit confused too when I first started working with web technologies, so I hope this helps you out!

Resources