Get data from Ajax in ASP.NET Core not working? - asp.net-core

I'm new at ASP.NET Core, and this is how I get data from Ajax.
I have a View Model like this
public class RequestSearchDefaultModel
{
public string FromToDate { get; set; }
public int Status { get; set; }
public List<SelectListItem> StatusType { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public IEnumerable<RequestViewModel> requestViewModel { get; set; }
}
When I search the form, I use Ajax to get the data
function OpenSearch() {
var stt = $('#StatusDropDown').val();
var daterange = $('#daterange').val();
var url = "#Url.Action("Search","RequestApproval")";
var model = { FromToDate: daterange, Status: stt };
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
}).done(function (res) {
console.log("here");
$('#myTable').html(res);
})
}
This is controller
[HttpPost]
public async Task<IActionResult> Search([FromBody] RequestSearchDefaultModel m)
{
m.FromDate = DateTime.Parse(m.FromToDate.Substring(0, 10)).Add(new TimeSpan(00, 0, 0));
m.ToDate = DateTime.Parse(m.FromToDate.Substring(14)).Add(new TimeSpan(23, 59, 59));
var request = _headerService.Search();
m.requestViewModel = _mapper.Map<IEnumerable<RequestViewModel>>(request);
return PartialView("_RequestBody", m);
}
This is the view
<div class="card-body">
<div class="table-responsive" id="myTable">
#Html.Partial("_RequestBody")
</div>
</div>
And this is the partial view
#model RequestSearchDefaultModel
<table class="table table-striped">
<thead>
<tr>
<th>Seq.</th>
<th>Title</th>
<th>Status</th>
<th>Draft Date</th>
<th>Final Approval Date</th>
</tr>
</thead>
<tbody id="RequestBody">
#if (Model.requestViewModel == null)
{
}
else
{
foreach (var item in Model.requestViewModel)
{
<tr>
<td>#item.ID</td>
<td>#item.DocumentNo</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID">#item.Title</a>
</td>
<td>#item.DraftDate</td>
</tr>
}
}
</tbody>
</table>
But I can't get the data, I don't know where I wrong, so please help. Thanks in advance.

Related

How to get related data with many-to-many relationship table?

I have three tables. The first one is Movie, the second one Category, and the third one MovieCategory. I listed movies, but I want to choose a category and then list the movies for each category.
How do I make the controller? I've included my business objects, view, and current controller below.
Movie Entity
public class Movie : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Summary { get; set; }
public string Director { get; set; }
public string Banner { get; set; }
public ICollection<MoviesCategory> MoviesCategory { get; set; }
}
Category Entity
public class Category : IEntity
{
public int Id { get; set; }
public string CategoryName { get; set; }
public ICollection<MoviesCategory> MoviesCategory { get; set; }
}
MovieCategory Entity
public class MoviesCategory : IEntity
{
public int Id { get; set; }
public int MovieId { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public Movie Movie { get; set; }
}
Controller
public IActionResult List()
{
var movies = _movieService.GetAll();
MovieListViewModel movieListViewModel = new MovieListViewModel()
{
Movies = movies
};
return View(movieListViewModel);
}
View
#foreach (var item in Model.Movies)
{
<tr>
#Html.HiddenFor(modelItem => item.Id)
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#if (!string.IsNullOrEmpty(item.Summary) && item.Summary.Length > 35)
{
<p>#(item.Summary.Substring(0,35))</p>
}
</td>
<td>
#Html.DisplayFor(modelItem => item.Director)
</td>
<td>
<img src="~/images/#item.Banner" width="105" height="140" class="img-thumbnail" />
</td>
<td>
<i title="Edit" class="fas fa-edit" style="color:coral"></i>
<i title="Detail" class="fas fa-info-circle" style="color:cornflowerblue"></i>
<td>
<tr>
}
In order to get a Category and its related Movies do the following:
Create a view model that holds the data for Category and Movies in order to have a strongly typed view:
public class MovieData
{
public Category Category { get; set; }
public IEnumerable<Movies> Movies { get; set; }
}
Then in your controller you query the database like this:
public async Task<IActionResult> MovieDataAction(int catId)
{
var data = await context
.Categories
.Where(c => c.Id == catId) //Category Id
.Include(c => c.MoviesCategory)
.ThenInclude(p => p.Movie)
.Select(cat => new { Category = cat, Movies = cat.MoviesCategory.Select(w => w.Movie) })
.FirstOrDefaultAsync();
var vData = new MovieData(){
Category = data.Category,
Movies = data.Movies
};
return View(vData);
}
I made a demo based on your description like below:
View:
#model MovieListViewModel
#{
ViewData["Title"] = "List";
}
<h1>List</h1>
#Html.DropDownListFor(modelItem => modelItem.CategoryId, Model.Categories, "Select Category",
new { #class = "form-control" })
<table>
#foreach (var item in Model.Movies)
{
<tr>
#Html.HiddenFor(modelItem => item.Id)
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#if (!string.IsNullOrEmpty(item.Summary) && item.Summary.Length > 35)
{
<p>#(item.Summary.Substring(0,35))</p>
}
</td>
<td>
#Html.DisplayFor(modelItem => item.Director)
</td>
<td>
<i title="Edit" class="fas fa-edit" style="color:coral"></i>
<i title="Detail" class="fas fa-info-circle" style="color:cornflowerblue"></i>
<td>
</tr>
}
</table>
#section scripts{
<script>
$("#CategoryId").on("change", function () {
var id = $(this).val();
window.location.href = "/Movie/List?id=" + id;
})
</script>
}
Controller:
public IActionResult List(int? id)
{
var movies = _context.Movies.ToList();
var categories = _context.Categories.ToList();
if(id != null)
{
movies = _context.MoviesCategories.Where(c => c.CategoryId == id).Select(m => m.Movie).ToList();
}
MovieListViewModel movieListViewModel = new MovieListViewModel()
{
CategoryId = id ?? 0,
Categories = new List<SelectListItem>(),
Movies = movies
};
foreach(var category in categories)
{
movieListViewModel.Categories.Add(new SelectListItem { Text = category.CategoryName, Value = category.Id.ToString() });
}
return View(movieListViewModel);
}
Result:

How to remove only images which are removed from webpage using Javascript

In ASP.Net Core MVC. I have created one product CREAT page which allows users to create product and upload multiple images of that product.
Now in editing page of this product I display all these pictures in <div> tag, with javascript of delete function to delete the picture which user want to remove and save the product details again.
From this point I don't understand how to tell ProductController.cs that which images should be deleted from database and which shouldn't.
Can someone put me on right direction, how exactly this process should work?
You can fire jquery call at each image delete; works for smaller set of images
You can store the deleted image-ids in an array and serialize the array to an hidden field and pass the array when you make one jquery call to ProductController.cs on edit submit.
You can check this repository for the solution
https://github.com/rajdeepdebnath/aspnetcore-mvc-collection
My view
#model List<WebApplication4.Controllers.Product>
#{
ViewData["Title"] = "Home Page";
}
#using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
if (Model != null)
{
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Desc</th>
<th>Images</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
var product = Model[i];
var id = $"product[{i}].Id";
var name = $"product[{i}].Name";
var description = $"product[{i}].Description";
<tr>
<td>#product.Id<input type="hidden" value="#product.Id" name='#id' /></td>
<td><input type="text" value="#product.Name" name='#name' /></td>
<td><input type="text" value="#product.Description" name='#description' /></td>
<td>
#foreach (var image in product.ImageIdArr)
{
<span class="image" data-imageid="#image" style="display:inline-block;width:20px;height:20px;background-color:darkseagreen;">😊</span>
}
</td>
</tr>
}
</tbody>
</table>
<input type="hidden" value="[]" name="DeleteImageIdArr" id="DeleteImageIdArr" />
<input type="submit" value="submit" />
}
}
#section Scripts{
<script>
$(document).ready(function () {
$('.image').click(function (v) {
console.log(v);
console.log(v.target.dataset.imageid);
var arr = [];
arr = JSON.parse($('#DeleteImageIdArr').val());
console.log(Array.isArray(arr));
if (arr.indexOf(v.target.dataset.imageid) < 0) {
arr.push(v.target.dataset.imageid);
}
$('#DeleteImageIdArr').val(JSON.stringify(arr))
console.log($('#DeleteImageIdArr').val());
console.log(v.target.hidden);
v.target.hidden = true;
});
$.ajax();
});
</script>
}
My controller
public class HomeController : Controller
{
public IActionResult Index()
{
var products = GetProducts();
return View(products);
}
[HttpPost]
public IActionResult Edit(List<Product> product, string[] DeleteImageIdArr)
{
var products = GetProducts();
return View("Index", products);
}
public List<Product> GetProducts()
{
var products = new List<Product> {
new Product{ Id=1, Name="Test 1", Description="Test 1", ImageIdArr=new int[]{ 1,2,3 } },
new Product{ Id=1, Name="Test 2", Description="Test 2", ImageIdArr=new int[]{ 4,5,6 } },
new Product{ Id=1, Name="Test 3", Description="Test 3", ImageIdArr=new int[]{ 7,8,9 } },
};
return products;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int[] ImageIdArr { get; set; }
}

Link in partial Razor Page fires wrong OnGet

I am using a razor page to display an ItemT model and at the bottom I inserted a partial view to show all properties (which are not assigned to this model in a n:m relation).
The PageModel 'FreePropertiesToItemT' has two public properties:
public ItemT ItemT { get; set; } // the one Item to show
public IList<PropertyIndexViewModel> FreeProperties { get; set; } // all free properties
An OnGetAsync(int? id) Method is called which works fine. The Page shows all data correctly.
The view displays a link for every Property:
<a asp-page-handler="addProperty" asp-route-id="#item.PropertyID">add</a>
This creates the link:
add
This is the correct link (I think). The route, id value and the handler are correct because there is a second OnGet Method in the PageModel:
public async Task<IActionResult> OnGetaddPropertyAsync(int? id)
However, the link only calls OnGetAsync (and not OnGetaddProppertyAsync) every time and, of course, for every Property!
What am I missing?
Model of ItemT:
public class ItemT
{
[Key]
public int ItemTID { get; set; }
[Required]
[StringLength(100, MinimumLength = 1)]
[Display(Name = "ItemT")]
public string Title { get; set; }
public bool isActive { get; set; } = true;
public virtual ICollection<ItemTProperty> ItemTProperties { get; set; }
}
ViewModel of free properties:
public class PropertyIndexViewModel
{
[Key]
public int PropertyID { get; set; }
[Required]
[StringLength(100, MinimumLength = 1)]
public string Title { get; set; }
public bool DefaultsOnly { get; set; }
[Display(Name = "Unit")]
public string Unit { get; set; }
[Display(Name = "Valuetype")]
public string Valuetype { get; set; }
}
The Page to list one ItemT:
#page
#model Inventory.Areas.Inventory.Pages.ItemTs.FreePropertiesToItemTModel
#{
ViewData["Title"] = "FreePropertiesToItemT";
}
<h1>Free Properties</h1>
<div>
<h4>ItemT</h4>
<hr />
<dl class="row">
<dt class="col-sm-2">
#Html.DisplayNameFor(model => model.ItemT.Title)
</dt>
<dd class="col-sm-10">
#Html.DisplayFor(model => model.ItemT.Title)
</dd>
<dt class="col-sm-2">
#Html.DisplayNameFor(model => model.ItemT.isActive)
</dt>
<dd class="col-sm-10">
#Html.DisplayFor(model => model.ItemT.isActive)
</dd>
</dl>
</div>
<div>
<a asp-page="./Edit" asp-route-id="#Model.ItemT.ItemTID">Edit</a> |
<a asp-page="./Index">Back to List</a>
</div>
<p></p>
<div>
#{
ViewData["FreeProperties"] = true;
}
<partial name="../Properties/_Properties.cshtml" model="Model.FreeProperties" />
</div>
The Partial which is loaded:
#using Inventory.DAL.ViewModels
#model IList<PropertyIndexViewModel>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model[0].Title)
</th>
<th>
#Html.DisplayNameFor(model => model[0].DefaultsOnly)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Unit)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Valuetype)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.DefaultsOnly)
</td>
<td>
#Html.DisplayFor(modelItem => item.Unit)
</td>
<td>
#Html.DisplayFor(modelItem => item.Valuetype)
</td>
<td>
#if (ViewBag.FreeProperties != null)
{
<a asp-page-handler="addProperty" asp-route-id="#item.PropertyID">add</a>
}
</td>
</tr>
}
</tbody>
</table>
And the c# code behind the page:
namespace Inventory.Areas.Inventory.Pages.ItemTs
{
public class FreePropertiesToItemTModel : PageModel
{
private readonly IUnitOfWork _uow;
public FreePropertiesToItemTModel(IUnitOfWork uow)
{
_uow = uow;
}
public ItemT ItemT { get; set; }
public IList<PropertyIndexViewModel> FreeProperties { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
ItemT = await _uow.ItemTRepo.getById((int)id);
if (ItemT == null)
{
return NotFound();
}
FreeProperties = await _uow.PropertyRepo.getFreePropertiesForItemT((int)id);
return Page();
}
public async Task<IActionResult> OnGetaddPropertyAsync(int? id)
{
if( id == null)
{
return NotFound();
}
if(ItemT == null) { return NotFound(); }
await _uow.ItemTRepo.addProperty(ItemT.ItemTID, (int)id);
await _uow.Commit();
return Page();
}
}
}
The issue is that your handler name error ,change it like below:
public async Task<IActionResult> OnGetAddPropertyAsync(int? id)
The first letter of handler name must be capitalized , otherwise handler=addProperty in the url is treated as a query-string parameter not a handler name.

partial view not displaying on main view post back

In the main view I am calling a partial view. It work fine for normal usage. On the postback the partial view controller bit is never triggered and the partial view does not displayed. What options are available to make sure that the partial view is rendered even when a postback is triggered.
Model:
public class ReportSummary
{
public int PayrollNumber { get; set; }
public string Name { get; set; }
public string ConflictInterest { get; set; }
public string SummaryConflictInterest { get; set; }
public string FinancialInterest { get; set; }
public string SummaryFinancialInterest { get; set; }
public string GiftInterest { get; set; }
public string SummaryGiftInterest { get; set; }
public string Combined { get; set; }
public string SummaryCombined { get; set; }
}
Controller:
Main:
public ActionResult CoiReporting()
{
...
var model = new ReportParamters();
model.Year = DateTime.Today.Year-1;
model.SelectedTab = "0";
...
return View(model);
}
[HttpPost]
[ActionName("CoiReporting")]
public ActionResult CoiReportingConfrim(string ViewReport, ReportParamters model )
{
...
switch (model.SelectedTab)
{
...
}
return View(model);
}
Partial:
public ActionResult _ReportCriteria(int Year=0, int ReportType=0, int Person=0, int Group=0, int Division=0, int Department=0, int Section=0, string SelectedTab="X")
{
...
var model = new ReportParamters();
model.Year = Year;
model.ReportType = ReportType;
model.Person = Person;
model.Group = Group;
model.Division = Division;
model.Department = Department;
model.Section = Section;
model.SelectedTab = SelectedTab;
return PartialView(model);
}
Views:
Main
#model ConflictOfInterest.Models.ReportParamters
#using (Html.BeginForm("CoiReporting", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.SelectedTab)
#Html.HiddenFor(model => model.Year)
<div id="tabs">
<ul>
<li>Summary</li>
<li>Statistics</li>
<li>Statistics with Person Detail</li>
</ul>
<div id="tabs-1">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
<input type="submit" name="ViewReport" id="ViewReport" value="View Report" class="SaveForm" />
<script type="text/javascript">
$(function () {
var sPath = "";
var sParam = "";
$("#tabs").tabs({
activate: function (event, ui) {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
....
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.newPanel.load(sPath + sParam);
},
active: $("#SelectedTab").val()
});
});
$('#tabs').click('tabsselect', function (event, ui) {
var selectedTab = $("#tabs").tabs("option", "active");
$("#SelectedTab").val(selectedTab);
});
</script>
}
Partial:
#model ConflictOfInterest.Models.ReportParamters
#{
if (Model.SelectedTab != "0")
{
<table border="0" cellpadding="0" cellspacing="0">
#{
if (Model.SelectedTab == "1")
{
<tr>
<td style="font-weight:bolder">#Html.Label("Year", "Year:")</td>
<td>#Html.DropDownListFor(model => model.Year, Enumerable.Empty<SelectListItem>(), (DateTime.Today.Year - 1).ToString(), new { #style = "width:200px;" })
</td>
<td style="font-weight:bolder">#Html.Label("ReportType", "Report Type:")</td>
<td>#Html.DropDownListFor(model => model.ReportType, new SelectList(ViewBag.ReportType, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">
#Html.Label("Person", "Person:")
#Html.Label("Group", "Group:")
</td>
<td>
#Html.DropDownListFor(model => model.Group, new SelectList(ViewBag.GroupList, "value", "Text"), new { #style = "width:200px;" })
#Html.DropDownListFor(model => model.Person, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })<br />
#Html.TextBox("sPerson")
<input type="button" id="bPerson" value="Search" />
</td>
</tr>
}
/*else
{
<tr>
<td colspan="6"></td>
</tr>
}*/
}
<tr>
<td style="font-weight:bolder">#Html.Label("Division", "Division:")</td>
<td>#Html.DropDownListFor(model => model.Division, new SelectList(ViewBag.Division, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Department", "Department:")</td>
<td>#Html.DropDownListFor(model => model.Department, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Section", "Section:")</td>
<td>#Html.DropDownListFor(model => model.Section, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
</tr>
<tr>
<td colspan="6"></td>
</tr>
</table>
}
else
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
}
}
The activate event of the jquery tab is triggered when a tab is activated(selected).
To ensure that the the same action is taking place on post back you need to use the create event as well.
Take note of the difference in the load at the end
create: function (event, ui) {
//event.preventDefault();
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
//console.log("Start Url: " + sUrl);
sPath = sUrl.substring(0, sUrl.lastIndexOf("?") + 1);
//console.log("Path: "+sPath);
//console.log("Parameters:"+sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length));
sParam = sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length)
var aParam = sParam.split("&");
for (var i = 0; i < aParam.length; i++) {
var aParama = aParam[i].split("=");
switch (i) {
case 7:
aParama[1] = selectedTab;
break;
}
aParam[i] = aParama.join("=");
}
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.panel.load(sPath + sParam);
},

Asp .net MVC...HttpPostedFileBase uploadImage is not always null

I want upload an Image but it always gets null. I'm using HttpPostedFileBase.
This is my COntroller
public ActionResult EmployeeDetail(EmployeeModel employee, HttpPostedFileBase UploadImage)//this UploadImage Object is always null
{
EmployeeModel employeeModel = new EmployeeModel();
if (string.IsNullOrEmpty(employeeModel.Name))
{
ModelState.AddModelError("Name", "Name is Required");
}
employeeModel.Name = employee.Name;
if (string.IsNullOrEmpty(employeeModel.DOJ))
{
ModelState.AddModelError("DOJ", "DOJ is Requird");
}
employeeModel.DOJ = employee.DOJ;
if (string.IsNullOrEmpty(employeeModel.DOB))
{
ModelState.AddModelError("DOB", "DOB is Required");
}
employeeModel.DOB = employee.DOB;
if (string.IsNullOrEmpty(employeeModel.Designation))
{
ModelState.AddModelError("Designation", "Designation is required");
}
employeeModel.Designation = employee.Designation;
string ImageName = Path.GetFileName(UploadImage.FileName);
string Physicalpath = Server.MapPath("~/images/" + ImageName);
UploadImage.SaveAs(Physicalpath);
employee.UploadImage = Physicalpath;
//string ImageName = Path.GetFileName(image.FileName);
//string physicalPath = Server.MapPath("~/images/" + ImageName);
//image.SaveAs(physicalPath);
// ModelState.AddModelError("UploadImage", "upload is required");
//employee.UploadImage = physicalPath;
EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
employeeBL.InsertDataRegistration(employeeModel);
return RedirectToAction("Index");
}
This is my View
#using (Html.BeginForm("EmployeeDetail", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" })) //i have used all the codes which could be need to make it work...still not working
{
<div class="MainDiv">
<table class="Table">
<tr class="Row">
<td class="Column1"> Name</td>
<td class="Column2">#Html.TextBoxFor(model => model.Name) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DOJ </td>
<td class="Column2">#Html.TextBoxFor(model => model.DOJ, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name) </td>
</tr>
<tr class="Row">
<td class="Column1">DOB</td>
<td class="Column2">#Html.TextBoxFor(model => model.DOB, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DESIGNATION</td>
<td class="Column2">#Html.TextBoxFor(model => model.Designation) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">UPlOAD </td>
<td class="Column2">#Html.TextBoxFor(model => model.UploadImage, new { #type = "File" })
</td>
</tr>
<tr class="Row">
<td colspan="2">
<input type="submit" class="button" name="submit" value="Submit">
<input type="reset" class="button1" value="Clear" name="Clear">
</td>
</tr>
</table>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/jquery-1.8.3.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/ui/minified/jquery-ui.custom.min.js"></script>
<script type="text/javascript">
$(function () {
// This will make every element with the class "date-picker" into a DatePicker element
$('.datepicker').datepicker();
})
</script>
</div>
}
this is my Model
public Model
{
public int EmployeeId { get; set; }
[Required(ErrorMessage = "this is required")]
public string Name { get; set; }
[Required (ErrorMessage = "This is required")]
public string DOJ { get; set; }
[Required(ErrorMessage ="This is required")]
public string DOB { get; set; }
[Required(ErrorMessage ="This is required")]
public string Designation { get; set; }
[Required(ErrorMessage = "This is required")]
public string UploadImage { get; set; }
public HttpPostedFileBase MyFile { get; set; }
}
I don't see anywhere you are passing any parameter to EmployeeDetail(). Are you able to get data for your EmployeeModel? If yes, then that at least confirm that your view able to call the EmployeeDetail() action.
Next, you need to make sure you are passing proper parameter to your EmployeeDetail(). One of the way I could think of is to use ajax. So you can create an ajax call when submit button is clicked, and pass all your data and the uploaded file input in the ajax method.
This is an example of using ajax call with JQuery syntax to pass data to the action
var inputFiles = $('inpFile').val();
var actMethod = "#Url.Action("EmployeeDetail", "Index")"
var postData = {
"Name": $('inpName').val(),
"DOJ": $('inpDOJ').val(),
...
"UploadImage": inputFiles
}
$.ajax()
{
url: actMethod ,
data: postData,
type: "POST",
success: function (data) {
alert("Insert Successful!");
}
}