Check out this page in {0} translated from {1}translated fromOriginal:Translated:Automatic translation powered by Microsoft® TranslatorStart translatingStop translatingCloseClose and show original pageSelectTotttttTasdfasdfasdfsadfTtttttttafsasdfasdfasdfasdfTo trun a ToTo pass File

Table of Contents

Pattern to Post Data using Jquery and Mvc
Html.Raw likes to ignore you
To use selectlist helper
To turn DataRow into Json
To add a function to a CSHTML page
To manage bookmarking
Areas
WTF !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
To render a _ view with no model
To render a partial view
To Render a partial (or any view) that does not need any data from the parent view
To display a date in proper format 'client side.
To 'turn off' validation for a specific field in a specific View
To format a date in a table etc. to show Time
To build out an object in javascript, build an array of the objects and an index for that array
Also Inline if while writing javascript
To generate javascript code from razor
To call javascript from razor
File upload pattern
Inline if
Inline to show a lookup in a table
Json -> Controller pattern
To render a view with a parameter
Really nasty artifact of Code First.... Validation required of fields that do not seem to be part of the field list.
To return a string to a client side alert box of all the errors
To simply show a C# var on the page. eg. status
To turn a 'create' page into an edit page
Steps to turn a standard template edit page into a 'ajax' edit page.
To get all the form fields in the controller (regardless if they have been re-hydrated as an object
To use razor to put a variable in Javascript
To conditionally display a variable with Razor
To send a value to the controller with a querystring
To format data on the scaffolded screens (eg. date, width)
To return a string from the controller (for jquery posts)
To bring Json objects on to the page for subsequent processing
To use the jquery datepicker with MVC3
File upload pattern
Action Filters




If returning a JSON result and you get a 'too long' message just overide the JsonResult method by putting this in your base controller or right in the controller


 
        //This ActionResult will override the existing JsonResult and will automatically set the
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonResult()
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                MaxJsonLength = Int32.MaxValue //Use this value to set your maximum size for all of your Requests
            };
        }
 










Pattern to Post Data using Jquery and Mvc


Jquery

 data = "{ email:'" + obin + "' , id: 2 }"
        url = "/messages/GetMessageData";
 
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            accept: "application/json",
            contentType: 'application/json, charset=utf-8',
            success: success,
            dataType: "json"
        });
 
 
 
        function success(data) {
            alert(data);
        }
 
Mvc

The object LeadEmail should match the json coming in.
public string GetMessageData(LeadEmail leadEmail)
        {
 
 
            int o = 0;
 
            return ("stuff");
        }
Also you need to register the json filter in Global.asax start


ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Then add this code to your controller method
 return Json(leadEmail, JsonRequestBehavior.AllowGet);
You can then access the object data on the client like such


dataIn.Id <- where id is a property of your object






Html.Raw likes to ignore you

this is the only syntax that will work

@Html.Raw(ga) <-- where ga is some string var ... no {} no ;



To use selectlist helper


@Html.DropDownList("deptId", Model.DeptsSL, new { onchange = "SetDepartments(this)", size=7, style="font-size:8pt" })
DeptSL is defined in the ViewModel

 public IEnumerable<SelectListItem> DeptsSL { get; set; }
It caned be filled from a table on the controller :

DataTable depts = dataFactory.GetDeptsByTermForUser(id, objLoginInfo.Acf2ID);
 
            dlvm.DeptsSL =  (from t in depts.AsEnumerable() select new SelectListItem { Value = t.Field<string>("SR_DEPT_CD").ToString(),  Text = t.Field<string>("SR_DEPT_NAME").ToString() }).ToList();
 



Routing VSIX for VX 2012

To turn DataRow into Json



      public static string GetJson(DataRow r)
        {
            int index = 0;
            StringBuilder json = new StringBuilder();
            foreach (DataColumn item in r.Table.Columns)
            {
                json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
                if (index < r.Table.Columns.Count - 1)
                {
                    json.Append(", ");
                }
                index++;
            }
            return "{" + json.ToString() + "}";
        }



To add a function to a CSHTML page


@functions{
    public string CheckUser(string enteredBy){
 
        if (enteredBy!=Model.enteredByCode)
        {
 
            PNNLCore.Opwhse.Person p = new PNNLCore.Opwhse.Person(enteredBy);
            Model.enteredByName = p.Name;
 
        }
        return Model.enteredByName;
    }
}
 
 
 
<span class="str">//call in code
 
@CheckUser("john")





To manage bookmarking


1. Use a jQuery plugin to process the url as it comes in

$.ajaxBookmarkable = function() { /* checks for any "hash params in url and if so changed them into GET params and resubmits page */
 
 if(window.location.hash.toString().match(/#/g)){
 
 //console.log("replacing hash");
 
 var arr = window.location.hash.toString().split('\#');
 
 var linka = window.location.protocol + "//" + window.location.host + window.location.pathname;
 
 window.location.replace(linka + '?' + arr[1]);
 
 }
 
 
 
 
 
 if (window.location.toString().indexOf("?") > -1) {
 
 //console.log("replacing querystring");
 
 var arr = window.location.toString().split('?');
 
 var linka = window.location.protocol + "//" + window.location.host + window.location.pathname;
 
 var url = linka + '#' + arr[1]
 
 
 
 if (!$.browser.msie) {
 
 window.history.pushState({ "html": "test1", "pageTitle": "test2" }, "new title", url);
 
 }
 
 
 
 }
 
 
 
 return false;
 
 }
2. call this in your layout page load

3. add an ActionFilterAttribute (see Action Filters)

4. add a block of code in the constructor of your page to process the vars from theActionFilterAttribute

 // for bookmarks
 
 if (OfferingType == "OFFERING") {
 
 //console.log("OFFERING");
 
 loadOffering(OfferingDialogItemId);
 
 }
 
 else if (OfferingType == "NEW") {
 
 //console.log("NEW");
 
 loadDetail(OfferingDialogItemId);
 
 }
 
 else if (OfferingType == "NEWDRAFT") {
 
 //console.log("NEWDRAFT");
 
 loadOffering(OfferingItemNum, OfferingDialogItemId);
 
 }





Areas


To develop an MVC website with areas you need to :

1. Add the area using the built tools in the VS (right click on the project and add area)
2. Modify the routes (in routeConfig.cs in MVC 4) to handle the multiple methods of the same name.

eg.

 routes.MapRoute(
 
 "Default",
 
 "{controller}/{action}/{id}",
 
 new { controller = "Home", action = "Index", id = UrlParameter.Optional },
 
 new[] { "ServiceCatalogMVC.Controllers" }
 
 );


WTF !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



The only syntax that renders a view from another controller

 @Html.Action("authHeader", "account")
exactly like that. no curly braces ... ahhhhhh


To render a _ view with no model


@Html.Partial("_LeadSystemHeader")




To render a partial view


THIS DOES NOT RENDER ANYTHING

 @{
 
 Html.Partial("_specifications");
 
 }
below renders fine. (go figure)
@Html.Partial("YourPartialViewName", Model)

To Render a partial (or any view) that does not need any data from the parent view

 @{Html.RenderAction("BuletinBoard");}



To display a date in proper format 'client side.

 var sttime = new Date('@Model.FirstOrDefault().finishTime');
 
 $("#finishTime").val(fntime.toShortDateString());
This assumes that the extended method for date
Date.prototype.toShortDateString = function () {
 
 return (this.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear();
 
};


To 'turn off' validation for a specific field in a specific View


@Html.TextBoxFor(model => model.mileageRate, new Dictionary<string, object> { { "data-val", false } })


To format a date in a table etc. to show Time


 @String.Format("{0:HH:mm tt}", item.finishTime.Value)
for date

 @String.Format("{0:MM/dd/yyyy }", item["startdate"])



To build out an object in javascript, build an array of the objects and an index for that array

Also Inline if while writing javascript


<script type="text/javascript">
 
 var dstart = null;
 
 var jobDaysIdx = new Array();
 
 var jobDays = new Array();
 
 var dnow = new Date();
 
 function DaysInMonth(month, year) {
 
 return new Date(year, month, 0).getDate();
 
 }
 
 // access like this
 
 alert(jQuery.inArray($("#date-1").val(), jobDaysIdx));
 
</script>
 
</script>
 
 @foreach (var item in Model)
 
 {
 
 <text><script type="text/javascript">jobDaysIdx[jobDaysIdx.length] = '@Html.Raw(item.jobDayDate.ToShortDateString())'</script></text>
 <text><script type="text/javascript">jobDays[jobDays.length] = jobDay = { date: '@Html.Raw(item.jobDayDate.ToString())',hours : @(item.timeRecord != null ? Html.Raw(item.timeRecord.hoursWorked.ToString()) : Html.Raw("0")), status : @Html.Raw(item.status.ToString()) };</script></text>
 
 }
 
 
 
 







sdfg
sdfg
sdfg
sdfg
xcvb

To generate javascript code from razor

 @foreach (var item in Model)
 
 {
 
 <text><script type="text/javascript">jobDates[jobDates.length] = '@Html.Raw(item.jobDayDate.ToString())';</script></text>
 
 }
 
 


To call javascript from razor



@{
 
 if (ViewBag.UserType != "1")
 
 {
 <script type="text/javascript">ShowPharmDiv(1);</script>
 }
 
 }

File upload pattern


1. View

<script type="text/javascript">
 
 $(document).ready(function () {
 
 // highjac the submit function
 
 $('#ajaxUploadForm').submit(function () {
 
 SubmitAjaxForm()
 
 return false;
 
 });
 
 });
 
 function SubmitAjaxForm() {
 
 // check to make sure that the file element has something in it
 
 if ($('#file').val().length == 0) {
 
 alert("Please choose a file");
 
 return;
 
 }
 
 document.getElementById("ajaxUploadForm").submit();
 
 }
 
 
 
</script>
 
<form id="ajaxUploadForm" action="@Url.Action("FileUpload", "Home")" method="post" enctype="multipart/form-data">
 
 <fieldset>
 
 <legend>Upload a file</legend>
 
 <label>
 <input type="hidden" value="@Model.process" id="process" name="process" />
 <input type="hidden" value="@Model.id" id="id" name="id" />
 <input type="file" id="file" name="file" /></label>
 <input id="ajaxUploadButton" type="submit" value="Submit" />
 </fieldset>
 
</form>
2. Server / controller
 public ActionResult FileUpload()
 {
 FileUpload fileUpload = new FileUpload();
 // only used to pass info with the upload
 fileUpload.id = int.Parse(Request.QueryString["id"]);
 fileUpload.process = Request.QueryString["process"];
 return View(fileUpload);
 }
 
 
 // This action handles the form POST and the upload
 [HttpPost]
 public ActionResult FileUpload(HttpPostedFileBase file)
 {
 
 // Verify that the user selected a file
 if (file != null && file.ContentLength > 0)
 {
 // extract only the fielname
 int id = int.Parse(Request.Form["id"]);
 string process = Request.Form["process"];
 string fileName = Path.GetFileName(file.FileName);
 // store the file inside ~/App_Data/uploads folder
 string path = Path.Combine(Server.MapPath("~/Documents"), fileName);
 file.SaveAs(path);
 SessionPersister.DocumentLocation = path;
 }
 
 // redirect back to the index action to show the form once again
 
 //return Json(new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) });
 
 return Content(string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)));
 
 
 
 }
3. In parent view

<div class="fl" style="width: 350px;">
 
 <iframe src="/Home/FileUpload?id=3" height="90px" width="390px" frameborder="0"></iframe>
 
 </div>




Inline if


@(item.approveDate.Year!=1? String.Format("{0:d}", item.approveDate):"")
@(Model.srNumber != null ? Html.Raw(Model.categoryDescription) : Html.Raw(""))


ReaJson
Trt;liasdhflkuhasdliufhasdliufhlasiudhfToSteTi one
Rear
On

Inline to show a lookup in a table


@(((IEnumerable<TempRxMVC.Models.ContactType>)ViewBag.contactTypes).Where(a => a.id.Equals(item.ContactTypeId)).FirstOrDefault().typeName)

Json -> Controller pattern



When you have an object on the client and you want to pass it to the controller
Client (build complex object)
 var Candidates = new Object();
 
 var candIds = new Array();
 
 var jobsSelected = 0;
 
 function SetJob(obin) {
 
 Candidates.jobid = $("#companyJobs").val();
 
 }
 
 function AddCandidate(obin) {
 
 jobsSelected++;
 
 $("#candsSel").html(jobsSelected);
 
 arRetval = obin.id.split("-");
 
 candIds[candIds.length] = arRetval[1];
 
 }
 
 
 function SendCandidates() {
 Candidates.candidateIds = candIds;
 jsCandidates = $.toJSON(Candidates);
 $.post("/PharmacyJobs/MatchJobs", { jsCandidates: jsCandidates },
 function (data) {
 alert("im back");
 });
 }
Controller
1. Add a class for an attribute decoratation

public class FromJsonAttribute : CustomModelBinderAttribute
 {
 private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
 
public override IModelBinder GetBinder()
 
 {
 
 return new JsonModelBinder();
 
 }
 
 private class JsonModelBinder : IModelBinder
 
 {
 
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 
 {
 
 var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
 
 if (string.IsNullOrEmpty(stringified))
 
 return null;
 
 return serializer.Deserialize(stringified, bindingContext.ModelType);
 
 }
 
 }
 
 }
2. In the action result method, remember to bring the object in with the same name as the posted name
 [HttpPost]
 
 public ActionResult MatchJobs([FromJson]Candidates jsCandidates)
 
 {
 int o = 0;
 return null;
 }

To render a view with a parameter


@{
 
 
 
 Html.RenderAction("ShowContacts", "PharmacyJobs", new { id = ViewBag.jobCandidateId });
 
 
 
 }



Really nasty artifact of Code First.... Validation required of fields that do not seem to be part of the field list.


These fields are typically fields that are part of an object relationship with the oject that you are working on.

Resolution:

Add Jquery .val entries ahead of the .post to populate these fields. eg

if you have a validation error for Company.id then put code jquery like:

$("#Company_id").val("3"); <-- notice that MVC will automatically change the id form . to dash but the name will still be with the .



To return a string to a client side alert box of all the errors


public static string ShowErrors(ModelStateDictionary errors)
 
 
 
 {
 
 
 
 ArrayList retVal = new ArrayList();
 
 
 
 for (int i = 0; i < errors.Values.Count; i++)
 
 
 
 {
 
 
 
 if (errors.Values.ElementAtOrDefault(i).Errors.Count > 0)
 
 
 
 {
 
 
 
 string thisError = "Field : " + errors.Keys.ElementAtOrDefault(i) + " - Value : " + errors.Values.ElementAtOrDefault(i).Value.AttemptedValue + "\n";
 
 
 
 retVal.Add(thisError);
 
 
 
 }
 
 
 
 }
 
 
 
 StringBuilder sb = new StringBuilder();
 
 
 
 for (int i = 0; i < retVal.Count; i++)
 
 
 
 {
 
 
 
 sb.Append(retVal[i].ToString());
 
 
 
 }
 
 
 
 return sb.ToString();
 
 
 
 }

To simply show a C# var on the page. eg. status



@status

To turn a 'create' page into an edit page


add a hidden input with the id.
 @{if (Model != null)
 
 
 
 {
 
 
 
 <input type="hidden" name="id" id="id" value="@Model.id" />
 
 
 
 }
 
 
 
 }

Steps to turn a standard template edit page into a 'ajax' edit page.


1. Tell the controller not to include any master pages.
Layout = null;
2. Add Javascript / jquery code for page navigation

<script type="text/javascript">
 
 
 
 
 
 
 
 var companyid = @Html.Raw(Model.Company.id.ToString())
 
 
 
 function ManagePharmacists() {
 
 
 
 $("#mainBody").load("/Pharmacists/Index?type=pharmacy&id=" + companyid)
 
 
 
 }
 
 
 
 function ManageAddress() {
 
 
 
 
 
 
 
 $("#mainBody").load("/Addresses/Create?type=pharmacy")
 
 
 
 }
 
 
 
 function PostAddress() {
 
 
 
 if ($("#AddressesEditForm").validate().form()) {
 
 
 
 $.post("/Addresses/Create",
 
 
 
 $("#AddressesEditForm").serialize(),
 
 
 
 
 
 function (data2) {
 
 
 
 if (data2 == "0") {
 
 
 
 $("#mainBody").html("").load("/Pharmacies/Edit/"+ companyid)
 
 
 
 }
 
 
 
 });
 
 
 
 }
 
 }
 
 
 
 function PostPharmacy() {
 
 
 
 if ($("#PharmacyEditForm").validate().form()) {
 
 
 
 $.post("/Pharmacies/Edit",
 
 
 
 $("#PharmacyEditForm").serialize(),
 
 
 
 function (data2) {
 
 
 
 if (data2 == "0") {
 
 
 
 $("#mainBody").html("").load("/Pharmacies/Index?type=company&Id="+ companyid)
 
 
 
 }
 
 
 
 });
 
 
 
 }
 
 
 
 }
 
 
 
 function BackToPharmacies(){
 
 
 
 $("#mainBody").load("/Pharmacies/Index")
 
 
 
 }
 
 
 
</script>

3. Wrap the main section of the page in a div that defines the workspace.

<divclass="StdPageBox">

4. Change the Html.BeginForm to be more complete ;eg.

@using (Html.BeginForm("Edit", "Pharmacies", FormMethod.Post, new { id = "PharmacyEditForm" }))
5. Change all the links from direct controller links to javascript function calls eg.

from:
 
 
 
@.ActionLink("Back to List", "Index")
 
 
 
 
 
to:
 
 
 
 
 
 function BackToEdit(){
 
 
 
 $("#mainBody").load("/Pharmacies/Edit")
 
 
 
 }




To get all the form fields in the controller (regardless if they have been re-hydrated as an object


[HttpPost]
 
 
 
 public ActionResult PlacementPreferences(FormCollection formCollection)
You can also just use Request.Form["foo"]

To use razor to put a variable in Javascript


var companyid = @Html.Raw(Model.id.ToString())

To conditionally display a variable with Razor

 @{ if (ViewBag.companyName!=null)
 
 
 
 {
 
 
 
 <text> for : @ViewBag.companyName</text>
 
 
 
 }
 
 
 
 }


To send a value to the controller with a querystring


 $(".StdPageBox").load("/Addresses/Create?type=company")
on the controller side we can catch that value like this
public ActionResult Create(string type)
 
 
 
 {
 
 
 
 }
variable name must match the name on the querystring.



To format data on the scaffolded screens (eg. date, width)


Decorate the class with:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]

You can also generate inline styling

@Html.TextBoxFor(model => model.userQuestion, new { style = "width:300px" })

Or link to a Css class

@Html.EditorFor(m => m.Name, new { @class = "myCss" })



asdfsdfTasdfasdfasdfasdfasdf

To format asdfasdf

To return a string from the controller (for jquery posts)


return Content("Hi there!");


For ramdom notes on Models / View / Controllers - Razor syntax - MVC 3 +

To expose the raw form posts the arrive at the controller use: FormCollection

eg. public ActionResult ProfilePharmacyExperience(FormCollection collection)


----------------------------------------------------




Html.RenderPartial("ProfilePharmacyExperienceItem",, item); does not seem to go back to the controller. Hence if you are using it you should pass in the data that it needs. Useful for loops in a calling page

@Html.Action("ProfilePharmacyExperience") hits the controller




Return values from Jquery posts


function PostExperiences() {
 
 
 
 if ($("#PharmacyExperienceForm").validate().form()) {
 
 
 
 $.post("ContractorProfile/ProfilePharmacyExperience",
 
 
 
 $("#PharmacyExperienceForm").serialize(),
 
 
 
 function (result) {
 
 
 
 $("#Result").html(result.sResult)
 
 
 
 //alert(result.sResult);
 
 
 
 });
 
 
 
 }
 
 
 
 }



In this case we get back a simple object (result). It was built on the controller.

public class Result
 
 
 
 {
 
 
 
 public string sResult { get; set; }
 
 
 
 }
 
 
 
in the method ...
 
 
 
 Result result = new Result();
 
 
 
 result.sResult = "success";
 
 
 
 return Json(result);


You may need to decorate the controller with

[OutputCache(Duration=0)]

when doing jquery posts that return a list of items after the post.

Note: this can only appear on 'master' pages not on 'partial' pages.


Good article on ViewBag etc. Data persisting in MVC

---------------------------------------------

To bring Json objects on to the page for subsequent processing


On the Client

 $.getJSON('/PharmacyJobs/GetPharmacies/' + obin, function (data) {
 
 
 
 
 
 
 
 $.each(data, function (key, drop) {
 
 
 
 $('#selPharmacies')
 
 
 
 .append($('<option>', { value: drop.id })
 
 
 
 .text(drop.name));
 
 
 
 });
 
 
 
 
 
 
 
 });
On the server

 public class DropDown
 
 
 
 {
 
 
 
 public int id { get; set; }
 
 
 
 public string name { get; set; }
 
 
 
 }
 
 
 
 
 
 public class PharmacyJobsController : SecureController
 
 
 
 {
 
 
 
 private TempRxContext db = new TempRxContext();
 
 
 
 
 
 // json list
 
 
 
 public JsonResult GetPharmacies(int id)
 
 
 
 {
 
 
 
 List<DropDown> pharms = (from ret in db.Pharmacys where ret.region.id == id select new DropDown { id = ret.id, name = ret.pharmacyName }).ToList();
 
 
 
 return Json(pharms, JsonRequestBehavior.AllowGet);
 
 
 
 }



To use the jquery datepicker with MVC3



MVC has templated helpers. These are code that is executed base on the decoration on the class

For Example

1. Decorate the property with a typical data type

[DataType(DataType.Date)]

Note: You can also just do:

$("#endDate").addClass('date');

You should also be able to just add the class 'date' to an element to make the date picker work.


2. Then add a templated helper to the shared view folder

ie. Date.chtml

@using System.ComponentModel.DataAnnotations;
 
 
 
@model DateTime?
 
 
 
@Html.TextBox("", Model != null ? Model.Value.ToShortDateString() : "", new { @class = "date" })
3. Add a js file to the scripts dir
EditorHookup.js

$(document).ready(function () {
 
 
 
 function getDateYymmdd(value) {
 
 
 
 if (value == null)
 
 
 
 return null;
 
 
 
 return $.datepicker.parseDate("yy/mm/dd", value);
 
 
 
 }
 
 
 
 $('.date').each(function () {
 
 
 
 var minDate = getDateYymmdd($(this).data("val-rangedate-min"));
 
 
 
 var maxDate = getDateYymmdd($(this).data("val-rangedate-max"));
 
 
 
 $(this).datepicker({
 
 
 
 dateFormat: "mm/dd/yy", // hard-coding uk date format, but could embed this as an attribute server-side (based on the current culture)
 
 
 
 minDate: minDate,
 
 
 
 maxDate: maxDate
 
 
 
 });
 
 
 
 });
 
 
 
});
4. Make sure that the document ready IN THE ACTUAL VIEW CALLS THIS JS.
If you put it prior to the loading of the view then the date element will not get the key class of 'hasDatepicker' as one of your classes for your date element

<script src="@Url.Content("~/Scripts/EditorHookup.js")" type="text/javascript"></script>


File upload pattern


Research suggests that the best way to do a nonintrusive file upload is with an Iframe

Iframe tag

<iframe src="@Url.Action(MVC.Home.FileUpload())?id=3&Process=Resume" height="90px" width="390px" frameborder="0">


View

@model FileUpload
 
 
 
@{
 
 
 
 ViewBag.Title = "FileUpload";
 
 
 
 Layout = null;
 
 
 
}
 
 
 
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
 
 
 
<script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
 
 
 
<script src="@Url.Content("~/Scripts/jquery.blockUI.js")" type="text/javascript"></script>
 
 
 
<style type="text/css">
 
 
 
 body
 
 
 
 {
 
 
 
 font-family: "Segoe UI" , Verdana, Tahoma, Arial, "Helvetica Neue" , Helvetica, Sans-Serif;
 
 
 
 font-size: 75%;
 
 
 
 font-style: normal;
 
 
 
 font-weight: 600;
 
 
 
 }
 
 
 
</style>
 
 
 
<script type="text/javascript">
 
 
 
 $(document).ready(function () {
 
 
 
 
 
 
 
 // highjac the submit function
 
 
 
 $('#ajaxUploadForm').submit(function () {
 
 
 
 SubmitAjaxForm();
 
 
 
 return false;
 
 
 
 });
 
 
 
 });
 
 
 
 
 
 
 
 function SubmitAjaxForm() {
 
 
 
 // check to make sure that the file element has something in it
 
 
 
 
 
 
 
 if ($('#file').val().length == 0) {
 
 
 
 alert("Please choose a file");
 
 
 
 return;
 
 
 
 }
 
 
 
 document.getElementById("ajaxUploadForm").submit();
 
 
 
 }
 
 
 
</script>
 
 
 
<form id="ajaxUploadForm" action="@Url.Action(MVC.Home.FileUpload())" method="post" enctype="multipart/form-data">
 
 
 
 <fieldset>
 
 
 
 <legend>Upload a @Model.process</legend>
 
 
 
 <label>
 
 
 
 <input type="hidden" value="@Model.process" id="process" name="process" />
 
 
 
 <input type="hidden" value="@Model.id" id="id" name="id" />
 
 
 
 <input type="file" id="file" name="file" /></label>
 
 
 
 <input id="ajaxUploadButton" type="submit" value="Submit" />
 
 
 
 </fieldset>
 
 
 
</form>
 
 
 
 

Server code

 public virtual ActionResult FileUpload()
 
 
 
 {
 
 
 
 var fileUpload = new FileUpload { id = int.Parse(Request.QueryString["id"]), process = Request.QueryString["process"] };
 
 
 
 
 
 
 
 // only used to pass info with the upload
 
 
 
 return View(fileUpload);
 
 
 
 }



[HttpPost]
 
 
 
public virtual ActionResult FileUpload()
 
 
 
 {
 
 
 
 var fileUpload = new FileUpload { id = int.Parse(Request.QueryString["id"]), process = Request.QueryString["process"] };
 
 
 
 // only used to pass info with the upload
 
 return View(fileUpload);
 
 
 
 }
 
 
 
 // This action handles the form POST and the upload
 
 
 
 [HttpPost]
 
 
 
 public virtual ActionResult FileUpload(HttpPostedFileBase file)
 
 
 
 {
 
 
 
 // Verify that the user selected a file
 
 
 
 if (file != null && file.ContentLength > 0)
 
 
 
 {
 
 
 
 // this is for later use if we have contract docs.
 
 
 
 var contractId = SessionPersister.ContractId;
 
 
 
 var id = int.Parse(Request.Form["id"]);
 
 
 
 var process = Request.Form["process"];
 
 
 
 // extract only the fielname
 
 
 
 var fileName = Path.GetFileName(file.FileName);
 
 
 
 var path = Path.Combine(Server.MapPath("~/Documents"), fileName);
 
 
 
 file.SaveAs(path);
 
 
 
 var documentType = _db.DocumentTypes.FirstOrDefault(a => a.typeName == process);
 
 
 
 var document = new Document { DocumentTypeId = documentType.id, documentLocation = string.Format("/Documents/{0}", fileName) };
 
 
 
 switch (documentType.id)
 
 
 
 {
 
 
 
 case 1:
 
 
 
 document.ContractorId = SessionPersister.ContractorId;
 
 
 
 break;
 
 
 
 case 2:
 
 
 
 document.ContractId = contractId;
 
 
 
 break;
 
 
 
 }
 
 
 
 _db.Documents.Add(document);
 
 
 
 _db.SaveChanges();
 
 
 
 }
 
 
 
 return Content(string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)));
 
 
 
 }



Action Filters


Action filters can process the response or request prior to or after the Controller method.

The base ActionFilterAttribute class has the following methods that you can override:


public class QueryStringFilterAttribute : ActionFilterAttribute
 
 {
 
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 
 {
 
 base.OnActionExecuting(filterContext);
 
 
 
 var qstring = filterContext.RequestContext.HttpContext.Request.QueryString;
 
 
 
 if (qstring.AllKeys.Count()>0)
 
 {
 
 
 
 for (int i = 0; i < qstring.AllKeys.Count(); i++)
 
 {
 
 switch (qstring.AllKeys[i]){
 
 
 
 case "CurrentCatalogLevelId":
 
 SCController.CurrentCatalogLevelId = qstring[i].ToString();
 
 break;
 
 
 
 case "Search":
 
 SCController.Search = qstring[i].ToString();
 
 break;
 
 
 
 case "CurrentCatalogMode":
 
 SCController.CurrentCatalogMode = qstring[i].ToString();
 
 break;
 
 
 
 case "OfferingDialogItemId":
 
 SCController.OfferingDialogItemId = qstring[i].ToString();
 
 break;
 
 
 
 
 
 }
 
 }
 
 
 
 }
 
 if (SCController.CurrentCatalogLevelId == null)
 
 {
 
 SCController.CurrentCatalogLevelId = "1";
 
 }
 
 
 
 
 
 SCController.qString = qstring.ToString();
 
 
 
 }
 
 }
















code

code