Uploading an image in ASP.NET MVC using EDM - c#

I am new to using ASP.NET MVC and I've been having some difficulties with it. I created my model using the Entity Data Model just for the record.
My problem is that I'm trying to insert an image into my MS SQL 2008 server using my new ASP.NET page. The image is a part of the information that I need to store about Employees in my database. From my home HomeController.cs file I right-clicked the Create method and chose to create a view, which it did. However, uploading an image was not part of the auto-generated code.
In the Create View there are a few text-boxes that correspond to my table columns and a single submit button that creates my new database row somehow. I thought that the button would run the code for the other Create method in the HomeController.cs file that takes an Employee as a parameter but I guess my problem lies in the fact that I don't know what happens between me pressing the Submit button and the creation of an Employee object for the Create method.
For reference, here is the code I'm working with .First code for Homecontroller.cs and then code for Create.aspx (note that the variable _db is a copy of my Entity Data Model):
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "employeeNumber")] Employee employeeToCreate)
{
try
{
_db.AddToEmployee(employeeToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I don't know why the code above indent's the way it does.
I also don't know why, but the code below doesn't show the first few lines properly so I deleted a few < > around C# code and asp code in order for the code to become visible.(FIXED)
<Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<LaunakerfiASP_MVC.Models.Employee>"
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) { %>
<fieldset>
<legend>Fields</legend>
<p>
<label for="name">name:</label>
<%= Html.TextBox("name")%>
<%= Html.ValidationMessage("name", "*")%>
</p>
<p>
<label for="email">email:</label>
<%= Html.TextBox("email")%>
<%= Html.ValidationMessage("email", "*")%>
</p>
<p>
<label for="department">department:</label>
<%= Html.TextBox("department")%>
<%= Html.ValidationMessage("department", "*")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
So what I would like to do is to add an element to the Create.aspx view that let's me upload an image to the column 'picture' in the table 'Employee'.

In your controller action, you can access the uploaded files through Request.Files
Here are some links about file uploads in ASP.NET MVC :
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
http://aspzone.com/tech/asp-net-mvc-file-upload/

Related

Html.ValidationMessageFor not showing

I have a MVC2 Project using ADO.NET Entity Data Model that I used to generate my view automatically since it has tons of fields. It gave me code like this.
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<div class="editor-label">
<%= Html.LabelFor(model => model.Position) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Position) %>
<%= Html.ValidationMessageFor(model => model.Position) %>
</div>
But with a ton more fields.
Here is my Controller code:
MyProjectEntities_Career_Applications dbca = new MyProjectEntities_Career_Applications();
[HttpPost]
public ActionResult Apply(Career_Applications application)
{
if (ModelState.IsValid)
{
//save form
dbca.AddToCareer_Applications(application);
dbca.SaveChanges();
}
else
{
ModelState.AddModelError("", "Application could not be submitted. Please correct the errors below.");
}
//redirect to thank you page
return View("Apply", application);
}
When the ModelState.IsValid fails I see the <%= Html.ValidationSummary(true) %> but none of the Html.ValidationMessageFor's ever show up.
What am I missing?
Turns out the problem was with the CSS. Stupid mistake, ugh!
Thanks for the help regardless.
I think you're missing a Jquery reference or error handling library that you're using.
This also happens often when you include validation script multiple times. (In shared view, and in your view)

Dynamically change style attributes in ASP.NET MVC

I'm reading percentages from a database, then use that number to create a bar showing visual progress. I need to do something like this on my aspx page:
<%
if (ViewData["width"] != null){
<div style="width: <%: ViewData["width"] %>px;"
</div>
}%>
Of course the above method doesn't work, but hopefully you can see what im trying to achieve. How do i change style attributes dynamically in ASP.NET MVC?
You just wrote HTML in the middle of a code block. You need to put your HTML outside the code block.
<% if (ViewData["width"] != null) { %>
<div style="width: <%: ViewData["width"] %>px;"></div>
<% } %>
Alternatively, you could switch to the Razor language which does away with all the <% %>s and allows you to intersperse C# and HTML much easier. It looks like this:
#if (ViewBag.width != null) {
<div style="width: #(ViewBag.width)px;"></div>
}
Your method should work, you just need to put the div code outside of the server block.
<% if (ViewData["width"] != null){ %>
<div style="width: <%: ViewData["width"] %>px;"
</div>
<% } %>

Launch a website through button click in excel

I have an mvc app which is integrated to excel workbook. I have a "Launch" button in excel which on click should launch the following website:
http://students/SubmitComments/
Here is my controller action:
public ActionResult StudentComment(string sid)
{
SubmitCommentViewModel model = new SubmitCommentViewModel ();
model.sid = sid;
TempData["model"] = model;
return View(model);
}
Here is my view:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<STU.Models.StudentCommentViewModel>"
%>
<asp:Content ID="Content4" ContentPlaceHolderID="TitleContent" runat="server">
Student Comments
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageName" runat="server">
Student Comments</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="Form1" method="post" action="/Student/StudentCommentEmail/">
<label>
Run Number: <%= Html.DisplayFor(x => x.Id) %>
</label>
<br />
<br />
<textarea name="comment" cols="40" rows="5">
Enter comments here...
</textarea><br/><br/>
<input type="submit" value="Submit Comments" /><br />
</form>
</asp:Content>
You need to host your website somewhere. http://students/SubmitComments/ is not a valid url. You can't link your excel workbook to your Visual Studio hosted site. That only works within Visual Studio. Unless you setup Visual Studio to work with IIS Express.
If you want others to use this Excel workbook then you will have to host your mvc site somewhere that is publically, or at least internally accessible.

View with a lot of Components. Multiple Model Objects?

I am developing a little MVC app.
The problem: I have a view page which has a form to add events, a form to search for events and a list of events.
It's not a big deal to place the components in single views but I need them in one page. I want a permanent form above the list of events.
The problem is that I don't know what to choice as a model object for the view. If I choice a List of events it's working perfectly with the List but not with the form. If I choice a specific Model Object fitting to the form the list hast problem.
What's the best way to handle such views with forms, lists,... ?
That's my View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="ViewPage<EventPlaza.Web.Models.EventsListViewModel>" %>
<%# Import Namespace="EventPlaza.Storage.Model" %>
<%# Import Namespace="EventPlaza.Web.HtmlHelpers" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="EventControlsContainer">
<h3>Add Event Link</h3>
<div>
<% Html.RenderPartial("AddEvent", new AddEventModel()); %>
</div>
<h3>Search for Events</h3>
<div>
<form>
Place:
<input id="elementID" name="elementID" type="text" class="inputSearch" />
Date:
<input id="datepicker" name="elementID2" type="text" class="inputSearch" />
<input id="addEvent" type="submit" value="Find Events" />
</form>
</div>
</div>
<% foreach(var product in Model.Events) { %>
<% Html.RenderPartial("EventSummary", product); %>
<% } %>
<div class="pager">
<%: Html.PageLinks(Model.PagingInfo,
x => Url.Action("List", new {page=x})) %>
</div>
</asp:Content>
This the AddEvent View Control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EventPlaza.Storage.Model.AddEventModel>"%>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("AddEvent", "Event", FormMethod.Post)) { %>
Event Link:
<%: Html.TextBoxFor(x => x.EventLink) %>
Event Name:
<%: Html.TextBoxFor(x => x.EventName) %><br />
Place:
<%: Html.TextBoxFor(x => x.Place) %>
Starting Date:
<%: Html.TextBoxFor(x => x.StartingDate) %> <br />
End Date:
<%: Html.TextBoxFor(x => x.EndDate) %>
<input id="Submit" type="submit" value="Add Event" />
<% } %>
I strongly recommend that you should not be using the Model object from the your Domain Model directly as the type of view instead you should make a custom EventViewModel and keep three different objects corresponding to each partial view you have.

Displaying a user control in ASP.NET MVC

This seemed easier in Web Forms; I'd have a user control, with the logic in the code-behind, and I could just drop it on a page.
But apparently code-behinds are a no-no in MVC, and the logic is in controllers. I'm a little confused about how logic for a user control is "wired up".
I want to display an RSS Feed user control. So I have a page:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
<% Html.RenderPartial("RssFeed"); %>
</p>
</asp:Content>
I have my user control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewPage<SyndicationFeed>" %>
<%# Import Namespace="System.ServiceModel.Syndication" %>
<p>
<%: ViewData.Model.Title.Text %>
</p>
<div>
<% foreach (var item in ViewData.Model.Items)
{
string url = item.Links[0].Uri.OriginalString;
%>
<p><a href='<%= url %>'><b><%= item.Title.Text %></b></a></p>
<% } %>
</div>
And I have this code that I need to run to get the rss data:
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}
But where does it go? In the controller for the page that contains the control?
To sum it up, this is how you can do it
[HttpGet, ChildActionOnly]
// put this in RssController
public ActionResult RssFeed()
{
// prepare the model
SyndicationFeed rssData;
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
rssData = SyndicationFeed.Load(reader);
}
return PartialView(rssData);
}
Usage:
<% Html.RenderAction("RssFeed", "Rss"); %>
And put a check into your ASCX if the Model you are sending in is null and if so, skip everything so it won't render anything. If you leave it like you have it now, it will end in an exception if the Model sent in is null.
Based on my understanding.... Yes, it can go in the controller in the page that contains the control. The partial can use the parent's ViewModel
See here (the bit on Partial Views)
http://msdn.microsoft.com/en-us/library/dd410123.aspx
EDIT
To include your RSS feed
If my controller were named RssController and it had a ViewResult method named RssFeed, I'd include the following on the .Master.
This causes the RssController to get invoked and return the view for your partial (assuming that's what View(rssData) sent back.
In ASP.NET MVC 2+, you can use Html.RenderAction to render an action's result inline.
Giving the action a [ChildActionOnly] attribute will prevent users from navigating to the action normally, making it usable only in this kind of "child" context.
I had a vaguely similar problem (using Razor view engine) which I solved by putting the code into the page since there wasn't anywhere else I wanted to put it. Mine actually related to rendering a menu.
The trick is to use the #functions { ... } construct.
Some pertinent info about the layout stuff here: http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx
Kind of like this in your case (not exactly right; it's late and I'm not on my dev box, but it hopefully gives the idea). That way you don't need any RSS controller at all if you are only doing this small piece of RSS related stuff.
#foreach (var item in RssFeed().Items)
{
<p><a href='#item.Links[0].Uri.OriginalString'><b>#item.Title.Text</b></a></p>
}
#functions {
public SyndicationFeed RssFeed()
{
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
return SyndicationFeed.Load(reader);
}
}
}

Categories