After Submit TotalPages Throws error - ajax

I have a little problem with my paging ("double TotalPage = #ViewBag.TotalPages; on Partial View"), after submiting on Create or Edit the paging throws the following error: "Cannot convert null to 'double' because it is a non-nullable value type". I have created a partial view that contains the list (Crud Operations using Ajax), all works fine, I can go to different pages in the list but when I submit a new row or edit an existing one it displays that error. Here is the code for it:
public ActionResult IndexApp(string Page)
{
var appc = objBs.appointmentdiaryBs.GetALL();
appc = from ac in db.tbl_Appoiment_Diary
select ac;
ViewBag.TotalPages = Math.Ceiling(objBs.appointmentdiaryBs.GetALL().Count() / 5.0);
int page = int.Parse(Page == null ? "1" : Page);
ViewBag.Page = page;
appc = appc.Skip((page - 1) * 5).Take(5);
ViewBag.Count = db.tbl_Appoiment_Diary.SqlQuery("SELECT * FROM dbo.tbl_Appoiment_Diary").Count();
return View(appc.ToList());
}
here is the partial view:
#model IEnumerable<BOL3.tbl_Appoiment_Diary>
<div class="table-responsive">
<table class="table" id="tbl" style="border-collapse: separate; border: solid grey 1px; border-radius: 6px; -moz-border-radius: 6px;">
<thead>
<tr style="background-color:aqua">
<th>
#Html.ActionLink("Title", "Title", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "Title", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th>
#Html.ActionLink("Scheduled Date and Time", "DateTimeScheduled", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "DateTimeScheduled", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th>
#Html.ActionLink("Appointment Lenght", "AppointmentLenght", "IndexApp", new { SortOrder = ViewBag.SortOrder == null ? "Asc" : (ViewBag.SortOrder == "Asc" ? "Des" : "Asc"), SortBy = "AppointmentLenght", page = (ViewBag.Page == null ? "1" : ViewBag.Page) })
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTimeScheduled)
</td>
<td>
#Html.DisplayFor(modelItem => item.AppointmentLenght)
</td>
<td style="align-content:center">
Edit |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
#{
double TotalPage = #ViewBag.TotalPages;
}
<ul class="pagination pagination-sm">
#for (int i = 1; i <= TotalPage; i++)
{
if (i == ViewBag.Page)
{
<li class="active">#Html.ActionLink(i.ToString() + " ", "IndexApp", new { SortOrder = (ViewBag.SortOrder == null ? "Asc" : ViewBag.SortOrder), SortBy = (ViewBag.SortBy == null ? "Title" : ViewBag.SortBy), Page = i })</li>
}
else
{
<li>#Html.ActionLink(i.ToString() + " ", "IndexApp", new { SortOrder = (ViewBag.SortOrder == null ? "Asc" : ViewBag.SortOrder), SortBy = (ViewBag.SortBy == null ? "Title" : ViewBag.SortBy), Page = i })</li>
}
}
</ul>
</div>
and here is the Index view:
<div id="main-div">
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div class="container">
Adauga
<br />
<div id="div-record1">
#Html.Partial("_Detail")
</div>
</div>
</div>

Related

.NET Core 6 Pull Down Menu Selection to Group through View Model

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

Validation and submit button don't function together in PartialView while using a composite model

Validation in my forms are defined in my Model.
If I don't include these two lines in my view:
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
The submit button works fine, but validation doesn't work. If I include these, validation starts working and the submit button doesn't work anymore.
I try to do the validation through my model.
My model:
public class TemplateDTO : DTOBase
{
public virtual int ID { get; set; }
[Required(ErrorMessage="فيلد ضروري")]
[RegularExpression("^[a-zA-z0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name { get; set; }
[RegularExpression("^[a-zA-zآ-ي0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name_Fr { get; set; }
public virtual IList<TemplateDetailsDTO> LstDetails { get; set; }
}
My composite model:
public class TemplateViewModel
{
public TemplateDTO Template { get; set; }
public List<TemplateFieldsDTO> TemplateFeilds { get; set; }
public int[] oSelectedFieldsDTO { get; set; }
public string Text { get; set; }
public bool NextLine { get; set; }
}
My Controller (ActionResult which calls the view and JsonResult which is the answer):
public ActionResult _NewTemplate()
{
if (myGlobalVariables.AllTemplateFieldsDTO == null)
{
TemplateFieldsClientService oTemplateFieldsClientService = new TemplateFieldsClientService();
myGlobalVariables.AllTemplateFieldsDTO = oTemplateFieldsClientService.GetAll();
}
TemplateDTO oTemplateDTO = new TemplateDTO();
oTemplateDTO.LstDetails = new List<TemplateDetailsDTO>();
TemplateViewModel x = new TemplateViewModel();
x.TemplateFeilds = myGlobalVariables.AllTemplateFieldsDTO;
x.Template = oTemplateDTO;
return PartialView(x);
}
[HttpPost]
public JsonResult _NewTemplate(TemplateViewModel oTemplateViewModel)
{
if (ModelState.IsValid)
{
if (oTemplateViewModel.Template != null)
{
if (oTemplateViewModel.Template.Name == null)
{
throw new System.ArgumentNullException("Parameter can not be null", "oTemplateDTO");
}
string strAttr = "";
if (oTemplateViewModel.NextLine)
strAttr = "\n";
List<TemplateDetailsDTO> LstTemDetails = new List<TemplateDetailsDTO>();
int Position = 0;
if (oTemplateViewModel.oSelectedFieldsDTO != null)
{
foreach (var i in oTemplateViewModel.oSelectedFieldsDTO)
{
TemplateDetailsDTO TempDetls = new TemplateDetailsDTO();
TempDetls.PositionNumber = ++Position;
TempDetls.Attributes = strAttr;
TemplateFieldsDTO OTemplateFieldsDTO = myGlobalVariables.AllTemplateFieldsDTO.Find(x => x.ID == i);
TempDetls.ObjFields = OTemplateFieldsDTO;
TempDetls.ObjTemplate = oTemplateViewModel.Template;
LstTemDetails.Add(TempDetls);
}
}
oTemplateViewModel.Template.LstDetails = LstTemDetails;
oTemplateClientService.AddNewTemplate(oTemplateViewModel.Template);
myGlobalVariables.AllTemplateDTO = oTemplateClientService.GetAllTemplate();
log.Info("Template added to Database.");
return Json(new { Result = "OK", Message = "عمليات ثبت با موفقيت انجام شد" }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها ي ضروري را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
Code for my view:
#model IAC.SMS.MvcApp.Controllers.TemplateViewModel
<script type="text/javascript">
$(function () {
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
$('#btnAdd').click(function () {
$('#ListBoxSource').find('option:selected').appendTo('#oSelectedFieldsDTO');
})
$('#btnDelete').click(function () {
$('#oSelectedFieldsDTO').find('option:selected').appendTo('#ListBoxSource');
});
$('#btnUp').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var prevOption = $('#oSelectedFieldsDTO').find('option:selected').prev("option");
if ($(prevOption).text() != "") {
$(selectedOption).remove();
$(prevOption).before($(selectedOption));
}
});
$('#btnDown').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var nextOption = $('#oSelectedFieldsDTO').find('option:selected').next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
});
});
function display() {
var dpt = document.getElementById("oSelectedFieldsDTO");
if (dpt.options[dpt.selectedIndex].text == "Text") {
document.getElementById("Text").disabled = false;
}
};
function SelectAllItems() {
$("#oSelectedFieldsDTO").each(function () {
$("#oSelectedFieldsDTO option").attr("selected", "selected");
});
};
//functions for ajax begin form
function Refresh() {
window.location.href = "#Url.Action("ListTemplate", "Template")" + "/";
}
function Success(data) {
if (data.Result == "OK") {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
Refresh();
}
else {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
}
function Fail() {
jSuccess(
'ارتباط برقرار نشد',
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
</script>
#using (Ajax.BeginForm("_NewTemplate", "Template", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "Success",
OnFailure = "Fail",
LoadingElementId = "Loading"
}, new { #id = "frmNewTemplate" }))
{
<table id="tblDetails" class="dataInput" style="width:500px;">
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مبدا
</label>
</td>
</tr>
<tr>
<td>
<label>
نام قالب
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name)
<label style="color:red; font-weight:bold;">*</label>
#Html.ValidationMessageFor(model => model.Template.Name)
</td>
<td></td>
<td rowspan="3">
#Html.ListBox("ListBoxSource", new SelectList(Model.TemplateFeilds, "ID", "Name", 1), new { size = 10 , style = "width:200px"})
</td>
</tr>
<tr>
<td>
<label>
توضيحات
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name_Fr)
</td>
</tr>
<tr>
<td>
<label>
پيام تکميلي
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Text , new { disabled="disabled"})
</td>
<td>
</td>
</tr>
<tr>
<td>
#Html.CH_CheckBoxFor(model=>model.NextLine, "خط بعد", false, false)
</td>
<td></td>
<td></td>
<td>
<button class="fixed button" id="btnAdd" type="button">اضافه<span class="left"></span> </button>
<button class="fixed button" id="btnDelete" type="button">حذف<span class="right"></span> </button>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مقصد
</label>
</td>
</tr>
<tr>
<td>
</td>
<td></td>
<td></td>
<td>
#Html.ListBoxFor(model => model.oSelectedFieldsDTO, new SelectList(Model.Template.LstDetails, "ID", "Name", 1), new { size = 10, style = "width:200px", onchange = "display()" })
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
</td>
<td>
<button class="fixed button" id="btnUp" type="button">بالا<span class="up"></span> </button>
<button class="fixed button" id="btnDown" type="button">پايين<span class="down"></span> </button>
</td>
</tr>
<tr>
<td>
#Html.HiddenFor(model=>model.Template.ID)
</td>
</tr>
</table>
<table>
<tr>
<td></td>
<td>
<div>
<button class="fixed button" type="submit" onmouseover="SelectAllItems()">ذخيره</button>
</div>
</td>
</tr>
</table>
}
Please tell me if I should include any more code.
My problem is that when I include the two lines code I mentioned above in my View to have validation, submit button in my PartialView won't function anymore, and the control doesn't go to the JsonResult function of my controller.
Thanks in Advance.
Update jquery.validate.min.js to version v1.12.0 - 4/1/2014 .
I hope you get the problem solved .

Video file upload using ajax in mvc 3

How can I upload any video format in my project. Is it the same as uploading image?,coz I can upload image but I can't upload any video. Any tips? Thank you.
I update my question,as I said I can upload image using the code below,my problem is how can I upload video at the same time and with some other data.
#model BookingCMS.Models.Booking
#{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.fileupload.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/jquery.fileupload-ui.css")" rel="stylesheet" type="text/css" />
<br />
<br />
<fieldset>
<legend>
<h2>
Add Movie</h2>
</legend>
<br />
<table id="table-2">
<tbody>
<tr>
<td>
Movie Name
</td>
<td>#Html.TextBoxFor(model => model.MovieName, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Status
</td>
<td>#Html.CheckBoxFor(model => model.Status)
</td>
</tr>
<tr>
<td>
Showing Type
</td>
<td>#Html.DropDownList("ShowingTypes", ViewBag.ShowingType as IEnumerable<SelectListItem>, "Select Type")
</td>
</tr>
<tr>
<td>
Movie Codes
</td>
<td>
<input class="checkbox" type="checkbox" id="SC" />
<label class="label">
Standard Cinema</label>
#Html.TextBoxFor(model => model.StandardCinema, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I2D" />
<label class="label">
IMAX2D</label>
#Html.TextBoxFor(model => model.Imax2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I3D" />
<label class="label">
IMAX 3D</label>
#Html.TextBoxFor(model => model.Imax3D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DC" />
<label class="label">
Directors Club</label>
#Html.TextBoxFor(model => model.DirectorsClub, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT2D" />
<label class="label">
Digital Theatre 2D</label>
#Html.TextBoxFor(model => model.DigitalTheatre2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT3D" />
<label class="label">
Digital Theatre 3D</label>
#Html.TextBoxFor(model => model.DigitalTheatre3D, new { #class = "textbox" })
</td>
</tr>
<tr>
<td>
Cast
</td>
<td>#Html.TextBoxFor(model => model.Cast, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Rating
</td>
<td>#Html.TextBoxFor(model => model.Rating, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Genre
</td>
<td>#Html.TextBoxFor(model => model.Genre, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Cinexclusive
</td>
<td>#Html.CheckBoxFor(model => model.Cinexclusive)
</td>
</tr>
<tr>
<td>
Blurb
</td>
<td>#Html.TextAreaFor(model => model.Blurb, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Synopsis
</td>
<td>#Html.TextAreaFor(model => model.Synopsis, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
#*#Html.TextBox("PosterHomepage", (string)ViewBag.PosterHomepage, new { #class = "editor-field" })*#
</td>
</tr>
<tr>
<td>
Running Time
</td>
<td>#Html.TextBoxFor(model => model.RunningTime, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Trailer
</td>
<td>#Html.TextBoxFor(model => model.Trailer, new { #class = "editor-field" }) #*Here is my problem ..how can I upload video with some other data*#
</td>
</tr>
</tbody>
</table>
<br />
<div style="float: left">
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnCancel" value="Cancel" />
</div>
</fieldset>
<script type="text/javascript">
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
});
$('#StandardCinema').hide();
$('#Imax2D').hide();
$('#Imax3D').hide();
$('#DirectorsClub').hide();
$('#DigitalTheatre2D').hide();
$('#DigitalTheatre3D').hide();
$('#SC').click(function () {
var check = $("#SC").is(':checked');//.attr('checked');
if (check == true) {
$('#StandardCinema').show();
$('#StandardCinema').focus();
}
else {
$('#StandardCinema').hide();
}
});
$('#I2D').click(function () {
var check = $("#I2D").is(':checked');
if (check == true) {
$('#Imax2D').show();
$('#Imax2D').focus();
}
else {
$('#Imax2D').hide();
}
});
$('#I3D').click(function () {
var check = $("#I3D").is(':checked');
if (check == true) {
$('#Imax3D').show();
$('#Imax3D').focus();
}
else {
$('#Imax3D').hide();
}
});
$('#DC').click(function () {
var check = $("#DC").is(':checked');
if (check == true) {
$('#DirectorsClub').show();
$('#DirectorsClub').focus();
}
else {
$('#DirectorsClub').hide();
}
});
$('#DT2D').click(function () {
var check = $("#DT2D").is(':checked');
if (check == true) {
$('#DigitalTheatre2D').show();
$('#DigitalTheatre2D').focus();
}
else {
$('#DigitalTheatre2D').hide();
}
});
$('#DT3D').click(function () {
var check = $("#DT3D").is(':checked');
if (check == true) {
$('#DigitalTheatre3D').show();
$('#DigitalTheatre3D').focus();
}
else {
$('#DigitalTheatre3D').hide();
}
});
$('#btnAdd').click(function () {
var e = document.getElementById("file_name");
var content = e.innerHTML;
//alert(content);
var _MovieName = $('#MovieName').val();
var _Active = $('#Status').val();
var _ShowingTypes = $('#ShowingTypes :selected').val();
var _ShowingTypesText = $('#ShowingTypes :selected').text();
var _Cast = $('#Cast').val();
var _Rating = $('#Rating').val();
var _Blurb = $('#Blurb').val();
var _Synopsis = $('#Synopsis').val();
var _RunningTime = $('#RunningTime').val();
var _Genre = $('#Genre').val();
var _Cinexclusive = $('#Cinexclusive');
var _Trailer = $('#Trailer').val();
var _PosterHomepage = content;
var _SC = $('#StandardCinema').val();
var _I2D = $('#Imax2D').val();
var _I3D = $('#Imax3D').val();
var _DC = $('#DirectorsClub').val();
var _DT2D = $('#DigitalTheatre2D').val();
var _DT3D = $('#DigitalTheatre3D').val();
var isSC = $("#SC").attr('checked') ? true : false;
var isI2D = $("#I2D").attr('checked') ? true : false;
var isI3D = $("#I3D").attr('checked') ? true : false;
var isDC = $("#DC").attr('checked') ? true : false;
var isDT2D = $("#DT2D").attr('checked') ? true : false;
var isDT3D = $("#DT3D").attr('checked') ? true : false;
var isActive = $('#Status').attr('checked') ? true : false;
var isCinex = $('#Cinexclusive').attr('checked') ? true : false;
if (_ShowingTypesText == "Select Type") {
alert("Showing Type is required.");
return false;
}
if (isSC == true & _SC == "") {
alert("Standard Cinema was selected! Movie code is required.");
$('#StandardCinema').focus();
return false;
}
if (isI2D == true & _I2D == "") {
alert("IMAX 2D was selected! Movie code is required.");
$('#Imax2D').focus();
return false;
}
if (isI3D == true & _I3D == "") {
alert("IMAX 3D was selected! Movie code is required.");
$('#Imax3D').focus();
return false;
}
if (isDC == true & _DC == "") {
alert("Director's Club was selected! Movie code is required.");
$('#DirectorsClub').focus();
return false;
}
if (isDT2D == true & _DT2D == "") {
alert("Digital Theatre 2D was selected! Movie code is required.");
$('#DigitalTheatre2D').focus();
return false;
}
if (isDT3D == true & _DT3D == "") {
alert("Digital Theatre 3D was selected! Movie code is required.");
$('#DigitalTheatre3D').focus();
return false;
}
var postData = {
moviename: _MovieName,
status: isActive,
showingtype: _ShowingTypes,
cast: _Cast,
rating: _Rating,
genre: _Genre,
cinexclusive: isCinex,
blurb: _Blurb,
synopsis: _Synopsis,
runningtime: _RunningTime,
trailer: _Trailer,
posterhompage: _PosterHomepage,
sc: _SC,
i2d: _I2D,
i3d: _I3D,
dc: _DC,
dt2d: _DT2D,
dt3d: _DT3D
};
$.ajax({
type: "POST",
url: "/Movies/CreateMovie",
dataType: "json",
traditional: true,
data: postData,
cache: false,
success: function (data) {
if (data.Result == "Success") {
jAlert(data.Message, "Notification", function () {
window.location = '/Home/Index';
});
}
else
jAlert(data.Message, "Notification"); //, function () {
//$('#code').focus();
//});
}
});
});
$("#btnCancel").click(function () {
window.location = "/Home/Index/";
});
</script>
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
ViewBag.PosterHomepage = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(r[0].Name));
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
[HttpPost]
public ActionResult CreateMovie(string moviename, bool status, int showingtype, string cast, string rating, string genre, bool cinexclusive, string blurb, string synopsis, string runningtime, string trailer, string posterhompage, string sc, string i2d, string i3d, string dc, string dt2d, string dt3d)
{
try
{
//Saving process
if (_WebResult.Result == 0)
{
return Json(new { Result = "Success", Message = _WebResult.Message.ToString() });
}
else
{
return Json(new { Result = "Error", Message = _WebResult.Message.ToString() });
}
}
catch (Exception)
{
return Json(new { Result = "Error", Message = "" + " failed to save." });
}
}

Open/View an Uploaded File using MVC3

I am trying to open or view an attachment(not save!) that a user uploaded into the Uploads folder on my website. The attachment feature will mainly be used for screen shots of bugs on the current website. I have a Bug Index view that shows all the bugs users have submitted and I would like to be able to view the attachment by clicking on the paper clip like a link. I just don't understand how to do something like this, do I need to use a partial view or some other helper method? I have attempted to write some methods to View the attachment but I don't think I am calling it correctly in my view. I have included the View Code and the controller code for the upload method and view attachment method. Please let me know if you need any other code for diagnosis. Thanks for your help!
Bug Index View
#model PagedList.IPagedList<DBFirstMVC.Models.bug>
#{
ViewBag.Title = "BugIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using PagedList;
<h2 class="corporate sifr">#ViewBag.Title</h2>
<div class="crossband">
#using (Html.BeginForm())
{
<div class="lefty">
Search Bugs Index: #Html.TextBox("SearchString", "", new { #class = "text" })
</div>
<input type = "submit" value = "Search" class = "button1" />
}
<div class="righty">
#Html.ActionLink("Report a Bug", "ReportBugs", "Support", null, new { #class = "button1" })
</div>
</div>
<div class="crossband">
<div class="lefty">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink("< Prev", "", new { page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "", new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink(">>", "", new { page = Model.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
<div class="righty">
Showing Records #Model.FirstItemOnPage to #Model.LastItemOnPage from #Model.TotalItemCount records
</div>
</div>
<table>
<tr>
<th>
#Html.ActionLink("Date Submitted", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "date_submitted"})
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "date_submitted"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "date_submitted"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Submitted By", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "submitted_by"})
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "submitted_by"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "submitted_by"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Description", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "Description" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "Description"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "Description"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Priority", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "Priority" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "Priority"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "Priority"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Estimated Completion Date", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "estimated_completion_date" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "estimated_completion_date"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "estimated_completion_date"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Status", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "status" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "status"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "status"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Developer Comments", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "developer_comments" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "developer_comments"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "developer_comments"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th>
#Html.ActionLink("Attachment", "BugIndex", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "attachment" })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "attachment"){<img id="asc" src="#Url.Content("~/Images/ico_tablesortoffset_asc.gif")" alt = "Asc Arrow" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "attachment"){<img id="desc" src="#Url.Content("~/Images/ico_tablesortoffset_desc.gif")" alt = "Desc Arrow" />}
</th>
<th></th>
</tr>
#{
var row_class = "odd";
}
#foreach (var item in Model)
{
row_class = row_class == "odd"? "even" : "odd";
<tr class="#row_class">
<td>
#Html.DisplayFor(modelItem => item.date_submitted)
</td>
<td>
#Html.DisplayFor(modelItem => item.submitted_by)
</td>
<td>
#Html.DisplayFor(modelItem => item.description)
</td>
<td>
#ViewBag.Priorities[(item.priority-1)].PRIORITY
</td>
<td>
#Html.DisplayFor(modelItem => item.estimated_completion_date)
</td>
<td>
#Html.DisplayFor(modelItem => item.status)
</td>
<td>
#Html.DisplayFor(modelItem => item.developer_comments)
</td>
<td>
#if (item.attachment != null){<img id="success" src="#Url.Content("~/Images/attach.png")" alt = "attachment" />}
#Url.Action("", "ViewAttachment", new { id = item.bug_pk}) <!--<----- I think this is the problem-->
</td>
<td>
#Html.ActionLink("Edit", "EditBugs", new { id = item.bug_pk }) |
#Html.ActionLink("Delete", "DeleteBugs", new { id = item.bug_pk })
</td>
</tr>
}
</table>
Controller Methods
[Authorize]
public String Uploadfile(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
int iteration = 1;
while (System.IO.File.Exists((path)))
{
fileName = string.Concat(fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(file.FileName));
path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
iteration++;
}
file.SaveAs(path);
}
return file.FileName;
}
public ActionResult ViewAttachment(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
return View(file.FileName);
}
Have an action method which accepts an ID to that purtiular Image resource. After uploading the image, you will have an id / path to the image, Show that in the grid as the HREF like this
#Html.ActionLink("View","ViewAttachment","Bugs",null,new { #id="SomeIdofImage"})
that will produce the HTML markup of an anchor tag like
View
The hardcoded SomeIdofImage should be replaced with your dynamic value ( the image Identifier)
Now have an action method in your Bug controller to read the Id as the parameter and return the image
public ActionResult ViewAttachment(string id)
{
var imgPath=SomeMethodtoGetTheFullPathToImg(id);
return File(imgPath, "image/jpeg")
}
Assuming you have a method SomeMethodtoGetTheFullPathToImg which accepts the ID and return the path to the Image stored in your server.
So I got this working and this is how I did it.
The ViewAttachment Controller was changed to allow system.IO methods
public ActionResult ViewAttachment(string fileName)
{
try
{
var fs = System.IO.File.OpenRead(Server.MapPath("~/Uploads/" + fileName));
return File(fs, "application/jpg", fileName);
}
catch
{
throw new HttpException(404, "Couldn't find " + fileName);
}
}
The View was modified to allow a paperclip image to be used for the link instead of the words download
<td>
#if (item.attachment != null)
{
<a href = #Url.Action("ViewAttachment", new { fileName = item.attachment }) > <img src = "#Url.Content("~/Images/attach.png")" alt = "attachment" /> </a>
}
</td>
The model went unmodified since I was using an existing database.
This is how I solved the problem that I was having viewing the images that were uploaded to the upload folder. This solution completely works with MVC 3 and MS SQL server 2008 R2.

Search by dropdown value using MVC 3

I am trying to create a search function that allows the user to search a column that is specified by a dropdown, I have been able to get the search to work but only by using a specific column and a contains method. Can anyone help?
Below I have included my controller and my view, please let me know if you need any other code. Thanks for your time and help!
I am almost positive that this is the code that I have to alter to use the dropdown to search instead of a specific column.
if (!String.IsNullOrEmpty(searchString))
{
IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper()));
}
Controller
public class PaController : Controller
{
PaEntities db = new PaEntities();
// Index Method
public ViewResult Index(string CurrentField, string sortField, string sortOrder, string currentFilter, string searchString, int? page, string Versions, string VPS, string Directors, string IAMP_SEARCH)
{
ViewBag.CurrentOrder = sortOrder = String.IsNullOrEmpty(sortOrder) ? "asc" : sortOrder; // Provides the order to sort
ViewBag.CurrentField = sortField = String.IsNullOrEmpty(sortField) ? "IAMP_PK" : sortField; // Provides the field to sort
var IAMP = from p in db.iamp_mapping select p;
var ISER = from s in db.iamp_search_string select s;
if (Versions != null && Versions != String.Empty) // Version Dropdown Sort Function
{
IAMP = IAMP.Where(v => v.VERSION.Contains(Versions));
}
var VIAMP = from x in db.version_number select x;
var VPIAMP = from v in db.vp_table select v;
var DIAMP = from d in db.director_table select d;
ViewData["SelectedVersion"] = Versions;
ViewData["Versions"] = new SelectList(VIAMP.Select(x => x.VERSION));
ViewData["VPS"] = new SelectList(VPIAMP.Select(x => x.VP));
ViewData["Directors"] = new SelectList(DIAMP.Select(x => x.DIRECTOR));
ViewData["currentFilter"] = currentFilter;
ViewData["IAMP_SEARCH"] = IAMP_SEARCH;
ViewData["IAMP_SEARCH"] = new SelectList(ISER.Select(x => x.IAMP_SEARCH));
if (Request.HttpMethod == "GET") {
searchString = currentFilter; //sets the currentFilter equal to Searchstring
IAMP_SEARCH = sortField;
}
else {
page = 1; // defaults to page 1
}
ViewBag.CurrentFilter = searchString; // Provides the view with the current filter string
if (!String.IsNullOrEmpty(searchString))
{
IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortField) {
default: IAMP = sortOrder == "asc" ? IAMP.OrderBy(p => p.PA) : IAMP.OrderByDescending(p => p.PA); break;
case "VERSION": IAMP = sortOrder == "asc"? IAMP.OrderBy(p => p.VERSION) : IAMP.OrderByDescending(p => p.VERSION); break;
case "MAJOR_PROGRAM": IAMP = sortOrder == "asc" ? IAMP.OrderBy(p => p.MAJOR_PROGRAM) : IAMP.OrderByDescending(p => p.MAJOR_PROGRAM); break;
case "INVESTMENT_AREA": IAMP = sortOrder == "asc" ? IAMP.OrderBy(p => p.INVESTMENT_AREA) : IAMP.OrderByDescending(p => p.INVESTMENT_AREA); break;
case "VP": IAMP = sortOrder == "asc" ? IAMP.OrderBy(p => p.VP) : IAMP.OrderByDescending(p => p.VP); break;
case "DIRECTOR": IAMP = sortOrder == "asc" ? IAMP.OrderBy(p => p.DIRECTOR) : IAMP.OrderByDescending(p => p.DIRECTOR); break;
}
int pageSize = 15; // number of records shown on page view
int pageNumber = (page ?? 1); // start page number
return View(IAMP.ToPagedList(pageNumber, pageSize)); // uses pagedList method to return correct page values
}
VIEW
#model PagedList.IPagedList<DBFirstMVC.Models.iamp_mapping>
#{
ViewBag.Title = "Index";
}
#using PagedList;
<h2 class="corporate sifr">PA Mapping</h2>
#using (Html.BeginForm())
{
<p>
Show Version: #Html.DropDownList("Versions","All")
<input type = "submit" value = "Go" />
</p>
}
#using (Html.BeginForm())
{
<div class="lefty">
Find by #Html.DropDownList("IAMP_SEARCH","All"): #Html.TextBox("SearchString")
<input type = "submit" value = "Search" />
</div>
}
<div class="righty">
#Html.ActionLink("Add a new PA to the database", "Create")
</div>
<br /><br />
<div>
<div class="lefty">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink("< Prev", "", new { page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "", new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink(">>", "", new { page = Model.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
<div class="righty">
Showing Records #Model.FirstItemOnPage to #Model.LastItemOnPage from #Model.TotalItemCount
</div>
</div>
<table>
<tr>
<th>
#Html.ActionLink("PA", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "PA", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "PA"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc"/>}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "PA"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc"/>}
</th>
<th>
#Html.ActionLink("MAJOR PROGRAM", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "MAJOR_PROGRAM", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "MAJOR_PROGRAM"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "MAJOR_PROGRAM"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc"/>}
</th>
<th>
#Html.ActionLink("INVESTMENT AREA", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "INVESTMENT_AREA", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "INVESTMENT_AREA"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc"/>}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "INVESTMENT_AREA"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc" />}
</th>
<th>
#Html.ActionLink("Version", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "VERSION", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "VERSION"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc" />}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "VERSION"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc"/>}
</th>
<th>
#Html.ActionLink("VP", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "VP", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "VP"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc"/>}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "VP"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc"/>}
</th>
<th>
#Html.ActionLink("DIRECTOR", "", new { sortOrder = ViewBag.currentOrder == "asc" ? "desc" : "asc", sortField = "DIRECTOR", Versions = ViewBag.SelectedVersion })
#if (ViewBag.currentOrder == "asc" && ViewBag.CurrentField == "DIRECTOR"){ <img src="../../Images/ico_tablesortoffset_asc.gif" alt = "table sort arrow asc"/>}
#if (ViewBag.currentOrder == "desc" && ViewBag.CurrentField == "DIRECTOR"){ <img src="../../Images/ico_tablesortoffset_desc.gif" alt = "table sort arrow desc"/>}
</th>
<th></th>
</tr>
#{
var row_class = "odd";
}
#foreach (var item in Model) {
row_class = row_class == "odd"? "even" : "odd";
<tr class="#row_class">
<td>
#Html.DisplayFor(modelItem => item.PA)
</td>
<td>
#Html.DisplayFor(modelItem => item.MAJOR_PROGRAM)
</td>
<td>
#Html.DisplayFor(modelItem => item.INVESTMENT_AREA)
</td>
<td>
#Html.DisplayFor(modelItem => item.VERSION)
</td>
<td>
#Html.DisplayFor(modelItem => item.VP)
</td>
<td>
#Html.DisplayFor(modelItem => item.DIRECTOR)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.PA}) |
#Html.ActionLink("Delete", "Delete", new { id = item.PA})
</td>
</tr>
}
</table>
<div>
<div class="lefty">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink("< Prev", "", new { page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "", new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
#Html.Raw(" ");
#Html.ActionLink(">>", "", new { page = Model.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, Versions = ViewBag.SelectedVersion })
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
<div class="righty">
Showing Records #Model.FirstItemOnPage to #Model.LastItemOnPage from #Model.TotalItemCount
</div>
</div>
<br /><br />
<div>
#Html.ActionLink("Download in Excel Format", "PaExcelOutput", new {Versions = ViewBag.SelectedVersion, currentFilter = ViewBag.currentFilter})
</div>
You could use Dynamic Query which allows you to use dynamic column names.

Resources