How to pass college ID of a admin based on his login details in Laravel - laravel-8

There's a college alumni portal, where the admin logins and he has to get in details of his colleges only based on the college ID (college ID will be specified by admin during registration and by students when they add their regno's).
How to pass the college ID during logging in so that only the details of the specific college based on admin college ID will be displayed?
class AdminAuthController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/admin/login';
public function registration()
{
return view('admin.auth.register');
}
public function create(array $data)
{
return Admin::create([
'collegeID' => $data['collegeID'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function signupsave(Request $request)
{
$request->validate([
'collegeID' => 'required|exists:college_names|unique:admins',
'email' => 'required|email|unique:admins',
'password' => 'required'
], [
// 'password.min' => 'The password must be at least 6 characters.',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("admin/login")->with('success', 'You have registered successfully.');
}
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
public function getLogin()
{
return view('admin.auth.login');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (auth()->guard('admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
$user = auth()->guard('admin')->user();
return view('admin.auth.dash1');
} else {
return back()->with('error', 'your username and password are wrong.');
}
}
public function dashboard(Request $request)
{
if (Auth::check()) {
return view('admin.auth.dash1');
} else
return Redirect::to("admin/login")->withSuccess('Oopps! You do not have access');
}
public function logout(Request $request)
{
$request->session()->flush();
Auth::logout();
return Redirect('admin/login');
}
}
public function index1(Request $request)
{
$collegeID=Admin::get('collegeID')->first();
//print($collegeID);
$data1['colleges'] = College::select('id', 'regno', 'collegeID')->where('collegeID',$collegeID)->get();
return view('admin.auth.index', $data1);
}
public function asd($id)
{
$id = auth()->user()->id;
print_r($id);
}
}
view:
<div class="row">
<div class="col-12 table-responsive">
<table class="table table-bordered user_datatable" id="user_datatable">
<thead>
<tr>
<center> <th><strong>ID</strong></th> </center>
<th><strong>Register Number</strong></th>
<!-- <th>College Name</th> -->
<th>College ID</th>
</tr>
</thead>
<tbody>
#foreach ($colleges as $college)
<tr align="center">
<td>{{ $college->id }} </td>
<td>{{ $college->regno }} </td>
<td>{{ $college->collegeID }} </td>
</tr>
#endforeach
</tbody>
</table>

Related

Razor Page Cascade Datatables by Dropdown

i have a dropdown list and i want to reload the datatable once i change the dropdown please note that the Checkbox field postback the page as well to update the database below is the cs file and will post the cshtml after
public class IndexModel : PageModel
{
private readonly IpponAcademy.Models.IJAContext _context;
public List<SelectListItem> judokaGroupList { get; set; }
[BindProperty]
public Boolean IsAttend { get; set; }
public IList<tbl_Judoka> tbl_Judoka { get;set; }
public IndexModel(IpponAcademy.Models.IJAContext context)
{
_context = context;
}
public void OnGet(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
}
below is the cshtml file, I'd appreciate finding a simple way to do refresh the datatable with the new selected field from the dropdown
#page
#model IpponAcademy.Pages.Attendance.IndexModel
#{
ViewData["Title"] = "Index";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<form method="post">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" asp-items="Model.judokaGroupList"></select>
#*onchange="alert(#Model.judokaGroupList)"*#
</div>
<table id="taskDt" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>
Attended
</th>
<th>
Code
</th>
<th>
Image
</th>
<th>
Judoka
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.tbl_Judoka)
{
var imagePath = #"UploadedFiles/" + item.J_Image;
<tr>
<td>
<input type="hidden" name="J_GUID" id="J_GUID" value="#item.J_GUID" />
<input asp-for="IsAttend" name="IsAttend" id="IsAttend" type="checkbox" onclick="this.form.submit()" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Code)
</td>
<td align="center">
<img src="#imagePath" alt="Judoka" width="50" height="50" class="rounded-circle mr-1" onclick="return LoadDiv(this.src);" style="cursor: pointer" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Name)
</td>
</tr>
}
</tbody>
</table>
</form>
#section scripts{
<script>
var table;
function LoadData() {
//alert('in');
table = $("#taskDt").DataTable({
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
}
$(document).ready(function () {
LoadData();
})
$("#ddlGroup").change(function () {
alert('DDLGroup');
//table.ajax.url("/Attendance/Index?handler=GET&Id=" + $("#ddlGroup Option:Selected").val()).load();
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
</script>
}
I think using window.location.href has been a simple enough way to refresh the datatable.Just one thing you need to improve,OnGet and OnGetJudoka method are the same,why not using just one method.
Change:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
To:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?Id=' + $("#ddlGroup Option:Selected").val();
});
If you must use another way,you could use form.submit():
Note:Be sure add name="id",otherwise the parameter will not bind to the backend.
<form method="post" asp-page-handler="Judoka">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" name="id" asp-items="Model.judokaGroupList"
onchange="this.form.submit()"></select>
</div>
</form>
Backend code:
Change:
public void OnGetJudoka(Guid? id)
To:
public void OnPostJudoka(Guid? id)
BTW,I also have a suggestion that you'd better maintain the selected value after postback :
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
//maintain the selected value after post back...
var selectedValue= judokaGroupList.Where(a => a.Value == id.ToString()).FirstOrDefault();
selectedValue.Selected = true;
//...
}

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);
},

How do i send the data to edit boxes on the same page?

i have the following page generated
when i click the Edit link, the record data must be sent to the input boxes on teh same page (without refreshing the page)
currently i have the controller code and views
controller: ProductCategory
public class ProductCategoryController : Controller
{
//
// GET: /ProductCategory/
TUDBEntities _db = new TUDBEntities();
public ActionResult Index(string Code)
{
var categories = _db.mt_ProductCategories
.Where(pc => Code == "" || Code == null|| pc.CatCode == Code)
.Select(
c => new ProductCategory {
Id = c.Id,
CategoryCode = c.CatCode,
Name = c.CatName,
Url = c.Url
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
[HttpPost]
public ActionResult Save(ProductCategory userData)
{
try
{
if (ModelState.IsValid)
{
mt_ProductCategories cat = new mt_ProductCategories { CatCode = userData.CategoryCode, CatName = userData.Name };
// TODO: Add insert logic here
_db.mt_ProductCategories.Add(cat);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
var category = _db.mt_ProductCategories
.Where(pc => pc.Id == id)
.Select(pc => new ProductCategory
{ Id=pc.Id, CategoryCode=pc.CatCode,Name=pc.CatName }).ToList();
return RedirectToAction("Index", category);
}
}
Index view
#model IEnumerable<eComm1.Models.ProductCategory>
#using(Ajax.BeginForm("Save", "ProductCategory",
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="prod-grid",
InsertionMode=InsertionMode.Replace,
OnSuccess="loaddivdata"
}))
{
<fieldset class="form-group">
<label for="Code">Category Code</label>
<input type="text" class="form-control focus" id="Code" name="CategoryCode" placeholder="Product category code" >
</fieldset>
<fieldset class="form-group">
<label for="ProdName">Product Name</label>
<input type="text" class="form-control" id="ProdName" name="Name" placeholder="Product Name">
</fieldset>
<button type="Submit" class="btn btn-primary">Save</button>
}
<hr />
<div id="prod-grid">
#Html.Partial("_ProductCategoryList", #Model)
</div>
<script type="text/javascript">
$(function () {
$('.focus :input').focus();
});
function loaddivdata() {
$('#prod-grid').html();
$('#Code, #ProdName').val('');
};
// $('#prod-grid').load(function () {
// $.ajax({
// url:'ProductCategoryController/Index',
// method:'GET',
// type:'application/html',
// success: function () { alert('called');}
// });
// });
//});
</script>
Partial View: _ProductCategoryList
#model IEnumerable<eComm1.Models.ProductCategory>
<div class="panel panel-default">
#if (Model.Count() == 0) { <div class="panel-heading">Product Categories - <span style='color:red;font-weight:bold' >0 RESULTS FOUND</span></div>
}else{
<!-- Default panel contents -->
<div class="panel-heading">Product Categories</div>
}
<!-- Table -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CategoryCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#*#Html.beActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })*#
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id=item.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", UpdateTargetId="", OnSuccess="loadformdata"})
</td>
</tr>
}
</table>
</div>
How do i modify my code to send data those input control and in my code how do i create hidden field for Id value so it can be send to the Edit(collection, int id) action to update the record?
for Stephen Muecke, i have added my jquery files through the bundles
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/ecomm").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-2.1.4.min.js",
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap.min.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"
));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/bootstrap.css",
"~/Content/style.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
In the partial view
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id = item.Id }, new AjaxOptions { HttpMethod = "GET", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", OnSuccess="loadformdata"})
in the index view the following js function:
function loadformdata() {
var cells = $(this).closest('tr').children('td');
alert(cells.eq(0).text());
//$('#Code').val(cells.eq(0).text());
//$('#ProdName').val(cells.eq(1).text());
}
To: Stephen Muecke:
i have removed above loadformdata() and put everything as you said. this youtube video shows the problem that still does not call that click event
To: Steven Meucke:
there's still no luck, for ease i have added a alert() in the function and the alert() won't show. Here is the video
Give you 'Edit' link a class name (say) class="edit" and handle its .click() event to update the form controls
$('.edit').click(function() {
var cells = $(this).closest('tr').children('td');
$('#Code').val(cells.eq(0).text());
$('#ProdName').val(cells.eq(1).text());
return false; // cancel the default redirect
});
Side note: You could just replace the ActionLink() code with Edit and the return false; line is not necessary.
write script for ajax call:
$('#edit').click(function () {
// var data = {here you will pass item.id }
$.ajax({
url:'ProductCategoryController/Edit',
data: {id : data}
method:'GET',
success: function (data) {
//clear html page here
//reload html page by passing 'data' passes in function
//e.g. suppose html page id is 'xyz' then $("#xyz").html(data)
}
});
});

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!");
}
}

POSt method for AJAX dynamically created input fields

I am using MVC and razor.
I have sucessfully implemented a way for the user to dynamically add more input rows at a click of a button (using AJAX and following Steven Sanderson's blog). BUT I do not know how to save the data to a database that the user inputs in these dynamically created fields.
I use his helper class, that quite frankly I am struggling to understand at all.
My question is what do I need to put in the POST create method. The link to the code in his blog is here:
steven sanderson's blog
Just a pointer in the right direction is all I need. THis is my current code:
New row partial view:
#model ef_tut.ViewModels.ClaimsViewModel
#using ef_tut.WebUI.Helpers
#using (Html.BeginCollectionItem("claims"))
{
<table class="editorRow">
<tr >
<td>
SubmissionUserID: #Html. EditorFor (o.claim.SubmissionUserID)
</td>
<td>
ClaimID: #Html.EditorFor(o => o.claim.ClaimID)
</td>
<td>
#Html.EditorFor(o => o.claim.ApprovedYN)
</td>
<td>
ClaimID(claimlinetable)#Html.EditorFor(o => o.claimline.ClaimID)
</td>
<td>
ClaimantUserID: #Html.EditorFor(o => o.claimline.ClaimantUserID)
</td>
<td>
Hours: #Html.EditorFor(o => o.claimline.Hours)
</td>
<td>
MileageCost: #Html.EditorFor(o => o.claimline.MileageCost)
</td>
<td>
TravelCost: #Html.EditorFor(o => o.claimline.TravelCost)
</td>
<td>
Hours cost: #Html.EditorFor(o => o.claimline.HoursCost)
</td>
<td>
Total cost: #Html.EditorFor(o => o.claimline.TotalCost)
</td>
<td>
ProxyYN: #Html.EditorFor(o => o.claimline.ProxyClaim)
</td>
<td>
CatID: #Html.EditorFor(o => o.claimline.CatID)
</td>
<td>
SubCatID: #Html.EditorFor(o => o.claimline.SubCatID)
</td>
<td>
delete
</td>
</tr></table>
}
Blankeditorrowmethod
public PartialViewResult BlankEditorRow()
{
return PartialView("NewRow", new ClaimsViewModel());
}
My current POST method that creates new DB records but all fields are null
[HttpPost]
public ActionResult Create(ClaimsViewModel viewModel)
{
if (ModelState.IsValid)
{
db.claims.Add(viewModel.claim);
db.claimlines.Add(viewModel.claimline);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
Create view
#model ef_tut.ViewModels.ClaimsViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>claim</legend>
<div id="editorRows"></div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
jquery
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
$("a.deleteRow").live("click", function () {
$(this).parents("table.editorRow:first").remove();
return false;
});
Steven's helper
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace ef_tut.WebUI.Helpers
{
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null)
{
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
}
Use FormCollection, so instead of this:
[HttpPost]
public ActionResult Create(ClaimsViewModel viewModel)
{
}
You will have this:
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
}
You should be able to get the value for any new fields you have created using their name like so:
var newFieldValue = formCollection["newFieldName"];