How to Save records to Master-detail tables in ASP.NET MVC 5 - asp.net-mvc

I have Test and Deta(Details) table in DB. With Entity Framework 5 I have obtained a model so I have classes generated from it. I also created controllers and views for the Deta table. I can add, clear and delete the records before saving but finally, I can't to save the records.
Test table has
(TestID,
MissionCode,
StartDate,
EndDate)
Deta table has
(DetaId,
TestType,
TestDate,
Driver,
Place,
TestID)
I used the following script in the view to add, clear and save the record.
#section scripts{
<script>
//Show Modal.
function addNewDeta() {
$("#newDetaModal").modal();
}
//Add Multiple Order.
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#testType").val()) == "" || $.trim($("#testDate").val()) == "" || $.trim($("#driver").val()) == "" || $.trim($("#place").val()) == "") return;
var testType = $("#testType").val(),
testDate = $("#testDate").val(),
driver = $("#driver").val(),
place = $("#place").val(),
detailsTableBody = $("#detailsTable tbody");
var tstItem = '<tr><td>' + testType + '</td><td>' + testDate + '</td><td>' + driver + '</td><td>' + place + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(tstItem);
clearItem();
});
//After Add A New Order In The List, Clear Clean The Form For Add More Order.
function clearItem() {
$("#testType").val('');
$("#testDate").val('');
$("#driver").val('');
$("#place").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove It.
$(document).on('click', 'a.deleteItem', function (e) {
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveDeta(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Detas/SaveDeta",
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveDeta").click(function (e) {
e.preventDefault();
var detaArr = [];
detaArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
detaArr.push({
testType: $(this).find('td:eq(0)').html(),
testDate: $(this).find('td:eq(1)').html(),
driver: $(this).find('td:eq(2)').html(),
place: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
missionCode: $("#missionCode").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
deta: detaArr
});
$.when(saveDeta(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
}
This is the controller
namespace WebApplication2.Controllers
{
public class DetasController : Controller
{
ETHADAMISEntities db = new ETHADAMISEntities();
public ActionResult Index()
{
List<Test> DetaAndTest = db.Tests.ToList();
return View(DetaAndTest);
}
public ActionResult SaveDeta(string missionCode, DateTime startDate, DateTime endDate, Deta[] deta)
{
string result = "Error! Test Detail Is Not Complete!";
if (missionCode != null && startDate != null && endDate != null && deta != null)
{
var tstId = Guid.NewGuid();
Test model = new Test
{
TestID = tstId,
MissionCode = missionCode,
StartDate = startDate,
EndDate = endDate
};
db.Tests.Add(model);
foreach (var item in deta)
{
var id = Guid.NewGuid();
Deta O = new Deta
{
DetaId = id,
TestType = item.TestType,
TestDate = item.TestDate,
Driver = item.Driver,
Place = item.Place,
TestID = tstId
};
db.Detas.Add(O);
}
db.SaveChanges();
result = "Success! Test with Detail Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
This is the view
#model IEnumerable<WebApplication2.Models.Test>
<br /><br />
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<h2 class="panel-title pull-left" style="margin-left:10px;">
<strong>Test Details</strong>
</h2>
<button style="margin-right:10px" class="btn btn-primary pull-right" onclick="addNewDeta()">New Test</button>
</div>
</div>
#*Receive All Database Data From Controller And Display Those Data In Client Side*#
#if (Model.Count() != 0)
{
foreach (var item in Model)
{
<div class="panel-body">
<table class="table table-striped table-responsive">
<tbody>
<tr>
<td>Mission Code : #item.MissionCode </td>
<td>Start Date : #item.StartDate </td>
<td>End Date : #item.EndDate</td>
</tr>
<tr>
<td colspan="3">
<table class="table table-bordered">
<tbody>
<tr>
<th>Test Type</th>
<th>Test Date</th>
<th>Driver</th>
<th>Place</th>
</tr>
#foreach (var deta in item.Detas)
{
<tr>
<td>#deta.TestType</td>
<td>#deta.TestDate</td>
<td>#deta.Driver</td>
<td>#deta.Place</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
}
}
else
{
<div class="panel-body">
<h3 style="color:red;">Empty!</h3>
</div>
}
</div>
#*Desing Bootstrap Modal With Order Form*#
<div class="modal fade" id="newDetaModal">
<div class="modal-dialog modal-lg" style=" width: 900px !important;">
<div class="modal-content">
<div class="modal-header">
×
<h4>Add New Test</h4>
</div>
<form id="NewDetailForm">
<div class="modal-body">
#*Test Details*#
<h5 style="color:#ff6347">Tests</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="TestID" />
<div class="form-group">
<label class="control-label col-md-2">
Mission Code
</label>
<div class="col-md-4">
<input type="text" id="missionCode" name="missionCode" placeholder="Mission Code" class="form-control" />
</div>
<label class="control-label col-md-2">
Start Date
</label>
<div class="col-md-4">
<input type="text" id="startDate" name="startDate" placeholder="Start Date" class="form-control" />
</div>
<label class="control-label col-md-2">
End Date
</label>
<div class="col-md-4">
<input type="text" id="endDate" name="endDate" placeholder="End Date" class="form-control" />
</div>
</div>
</div>
#*Test Detail Details*#
<h5 style="margin-top:10px;color:#ff6347">Test Details</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="DetaId" />
<div class="form-group">
<label class="control-label col-md-2">
Test Type
</label>
<div class="col-md-4">
<input type="text" id="testType" name="testType" placeholder="Test Type" class="form-control" />
</div>
<label class="control-label col-md-2">
Test Date
</label>
<div class="col-md-4">
<input type="datetime" id="testDate" name="testDate" placeholder="Test Date" class="form-control" />
</div>
<label class="control-label col-md-2">
Place
</label>
<div class="col-md-4">
<input type="text" id="place" name="place" placeholder="Place" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">
Driver
</label>
<div class="col-md-4">
<input type="text" id="driver" name="driver" placeholder="Driver" class="form-control" />
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">AddToList</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead>
<tr>
<th style="width:30%">Test Type</th>
<th style="width:20%">Test Date</th>
<th style="width:25%">Driver</th>
<th style="width:15%">Place</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveDeta" type="submit" class="btn btn-success">Save Test Detail</button>
</div>
</form>
</div>
</div>
</div>

Related

Change modal form depending on the button clicked

I have a table showing the information of the users, with an edit button for each one.
I want to show a modal form with the details for the user I want to edit, but I don't know how to get the details from the list, and passing them to the modal as a model.
Here is my View:
#model MyApp.Models.User
#{
ViewBag.Title = "Users";
var roles = new List<string> { "Manager", "Admin" };
var userRoles = (List<string>)ViewData["userRoles"];
}
<h2>#ViewBag.Title</h2>
#if (userRoles.Any(u => roles.Contains(u)))
{
using (Html.BeginForm("Update", "Admin", FormMethod.Post, new { id = "update-form", value = "" }))
{
<div class="modal fade" id="user-editor" >
<div class="modal-header">
<a class="close" data-dismiss="modal"><h3>×</h3></a>
<h3 id="modal-title">Edit User</h3>
</div>
<div class="modal-body">
<div class="form-group">
#Html.Label("Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Age", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Age, new { #class = "form-control" })
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
<input type="submit" class="btn btn-primary" value="Save Changes" />
</div>
</div>
}
}
<table class="table-bordered table-hover" id="tbusers">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
#if (userRoles.Any(u => roles.Contains(u)))
{
<th>Edit</th>
}
</tr>
</thead>
<tbody>
#foreach (var u in users)
{
<tr id="#u.Id">
<td>#u.Name</td>
<td>#u.Age</td>
#if (userRoles.Any(u => roles.Contains(u)))
{
<td><a type="button" class="btn edit-btn" href="#user-editor" data-toggle="modal">Edit</a></td>
}
</tr>
}
</tbody>
</table>
I've created a testing sample which will help you understand how can you achieve this.
Index.cshtml which will show a list of employees
#model IEnumerable<MvcApplication1.Models.Employee>
#using MvcApplication1.Models;
<h2>Index</h2>
<table>
#foreach (Employee item in Model)
{
<tr>
<td>#Html.ActionLink(#item.EmployeeName, "Name", new { id = item.ID })</td>
<td>
<button type="button" data-id='#item.ID' class="anchorDetail btn btn-info btn-sm" data-toggle="modal"
data-target="#myModal">
Open Large Modal</button></td>
</tr>
}
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
At the same page, reference the following scripts
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
JQuery AJAX call for getting/setting the data of individual employee from ActionMethod at the same page
<script>
$(document).ready(function () {
var TeamDetailPostBackURL = '/Employee/Details';
$(document).on('click', '.anchorDetail', function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('.modal-body').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
$("#closbtn").click(function () {
$('#myModal').modal('hide');
});
});
Now Create a class of Employee(because i'm not using EF)
public class Employee
{
public int ID { get; set; }
public string EmployeeName { get; set; }
}
Create controller named Employee and 2 ActionMethods like these:
public ActionResult Index()
{
return View(emp);//sends a List of employees to Index View
}
public ActionResult Details(int Id)
{
return PartialView("Details",
emp.Where(x=>x.ID==Convert.ToInt32(Id)).FirstOrDefault());
}
I'm returning PartialView because I need to load a page within a page.
Details.cshtml
#model MvcApplication1.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.ID)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.ID)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.EmployeeName)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.EmployeeName)
</div>
</fieldset>
<p>#Html.ActionLink("Back to List", "Index")</p>
When you execute and visit the Index page of Employee, you'll see screen like this:
And the Modal Dialog with results will be shown like this:
Note: You need to add reference of jquery and Bootstrap and you can further design/customize it according to your needs
Hope it helps!

Boostrap Modal not working on ASP.NET MVC

I have readed a lot of blogs and articles about showing MVC partial views using Boostrap modals. It seems that I have exactly what I'm seen on the material consulted but still it doesn't show the modal. I just need to show the partial view with the Album details in a modal. The controller is working fine when I load the URL through the browser.
This is the Index HTML code where the modal is shown:
<tbody>
#foreach( var album in Model.Albums)
{
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
}
</tbody>
Partial View
<div class="modal fade" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="albumModalLabel">Album Details</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<div class="row">
<label>Album<input class="form-control" type="text" id="title" /></label>
</div>
<div class="row">
<label>Artist <input class="form-control" type="text" id="artist" /></label>
</div>
<div class="row">
<label>Genre <input class="form-control" type="text" id="genre" /></label>
</div>
<div class="row">
<label>Year <input class="form-control" type="text" id="year" /></label>
</div>
</div>
<div class="col-md-8">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Track</th>
<th>Song Title</th>
<th>Length</th>
</tr>
</thead>
<tbody class="tracks"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
HomeController
[HttpGet]
public ActionResult Album(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var albumInfo = _service.GetAlbumInfo((int) id);
if (albumInfo == null) return HttpNotFound();
return PartialView("_Album", albumInfo);
}
Script
$(document).ready(function() {
$('.list-element').click(function () {
debugger;
var $buttonClicked = $(this);
var url = $buttonClicked.attr('data-url');
$.get(url, function (data) {
$('#albumContainer').html(data);
$('#albumModal').modal('show');
});
});
});
In almost all of the SO questions counsulted, they wasn't using data-target but I am. What do I need to modify to achieve that the modal shows?
VIEW
#model ShowModal
<table>
<tbody>
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModal">
#Html.Partial("_albumPartial", Model)
</div>
CONTROLLER
[HttpGet]
public ActionResult Album(int? id)
{
ShowModal modal = new ShowModal();
var albumInfo = _service.GetAlbumInfo((int) id);
modal.Info1 = albumInfo.Info1;//and other fields
return PartialView("_albumPartial", modal);
}
SCRIPT
<script>
$(document).ready(function () {
$("#albumModal").on("show.bs.modal", function (e) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // or button.attr("data-url") or get here just the id and create the URL here
$.get(url, function (data) {
$('#albumModal').html(data);
$('#albumModal').modal('show');
});
});
});
</script>

AngularJs , MVC During the Edit mode why Values not Binding in DropdownList

Im using Mvc with Angularjs here I am fetching data from Database using join and Display data in table when i click on Edit button that particular row is binding in Bootstrap "modal" but why country,State Names not binding in the dropdown.
Here i'm showing Linq query:
public JsonResult GetAssData()
{
var x = (from n in db.Accessors
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new { n.Id, n.Name, n.Email, n.Password, n.GEnder, n.Active, ctr.CountryName, sts.StateName, });
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult EditSer(int id = 0)
{
var x = (from n in db.Accessors
where n.Id == id
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new
{
n.Id,
n.Name,
n.Email,
n.Password,
n.GEnder,
ctr.CountryName,
sts.StateName,
});
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindCtry()
{
var x = from n in db.Countrys select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindStates(int Id = 0)
{
var x = from n in db.States
where n.CountryID == Id
select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
AngularJs
app.controller('MyBindCNtrls', function ($scope, MyBindServiceservice) {
GetAssusData();
function GetAssusData() {
var xxx = MyBindServiceservice.getAss();
xxx.then(function (d) {
$scope.access = d.data;
})
}
$scope.EditEmp = function (Emp) {
alert('in EditModes')
var sss = MyBindServiceservice.EditAssFun(Emp.Id);
sss.then(function (d) {
$scope.Id = Emp.Id;
$scope.Name = Emp.Name;
$scope.GEnder = Emp.GEnder;
$scope.Email = Emp.Email;
$scope.Password = Emp.Password;
$scope.CountryID = Emp.CountryID;
$scope.CountryName = Emp.CountryName;
$scope.StateName = Emp.StateName;
$scope.ValidAction = 'Update';
$('#Modalpopup').modal('show');
})
}
})
app.service('MyBindServiceservice', function ($http) {
this.getAss = function () {
var xx = $http({
url: '/Bindctrl/GetAssData',
method: 'Get',
params: JSON.stringify(),
content: { 'content-type': 'application/Json' }
})
return xx;
}
this.EditAssFun = function (Id) {
alert('enter in edit ser')
var sts = $http({
url: '/Bindctrl/EditSer',
method: 'Get',
params: {
Id: JSON.stringify(Id)
}
});
return sts;
}
});
<div ng-controller="MyBindCNtrls">
<table class="table table-bordered">
<tr>
<th><b>Id</b></th>
<th><b>Name</b></th>
<th><b>Email</b></th>
<th><b>Password</b></th>
<th><b>Gender</b></th>
<th><b>CountryName</b></th>
<th><b>StateName</b></th>
<th><b>Action</b></th>
</tr>
<tr ng-repeat="Accessor in access">
<td>{{Accessor.Id}}</td>
<td>{{Accessor.Name}}</td>
<td>{{Accessor.Email}}</td>
<td>{{Accessor.Password}}</td>
<td>{{Accessor.GEnder}}</td>
<td>{{Accessor.CountryName}}</td>
<td>{{Accessor.StateName}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" value="Edit" ng-click="EditEmp(Accessor)"><span class="glyphicon glyphicon-pencil"></span></button>
</td>
</tr>
</table>
<div class="modal" id="Modalpopup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>{{msg}}Login Details</h3>
</div>
<div class="modal-body">
<form novalidate name="f1" ng-submit="SaveDb(Ass)">
<div>
{{Errormsg}}
</div>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Name
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="nam" ng-model="Name" ng-class="Submittes?'ng-dirty':''" required autofocus />
<span class="Error" ng-show="(f1.nam.$dirty || Submittes) && f1.nam.$error.required">Enter Name</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Email
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="MailId" ng-model="Email" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.MailId.$dirty || Submittes) && f1.MailId.$error.required">Enter Email</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Password" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty || Submittes) && f1.psw.$error.required">Enter Password</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Gender
</div>
<div class="col-sm-8">
<input type="radio" value="Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Male
<input type="radio" value="Fe-Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Fe-Male
<br />
<span class="Error" ng-show="(f1.Gen.$dirty || Submittes) && f1.Gen.$error.required">Select Gender</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Country
</div>
<div class="col-sm-8">
<select class="form-control" name="cntrsy" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-model="CountryID" ng-change="GetStates()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.cntrsy.$dirty || Submittes) && f1.cntrsy.$error.required">Select Country</span>
{{CountryName}}
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
StateName
</div>
<div class="col-sm-8">
<select class="form-control" name="sts" ng-options="I.StateID as I.StateName for I in StateList" ng-model="StateID" ng-change="GetCitys()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.sts.$dirty || Submittes) && f1.sts.$error.required">Select States</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-sm btn-success pull-right" value="{{ValidAction}}" ng-class="SaveAndSubmit()" />
#* <input type="button" class="btn btn-sm pull-right" value="Cancel" id="BtnCancel" />*#
</div>
</form>
</div>
</div>
</div>
</div>
</div>

HttpPostedFileBase is coming null

below is the code in my View
#using ClaimBuildMVC.Models
#model IEnumerable<Asset>
#{
ViewBag.Title = "AssetsPage";
Layout = "~/Views/Shared/_SuperAdminLayout.cshtml";
}
<script type="text/javascript">
</script>
#using (Html.BeginForm("AssetsPage", "SuperAdmin", FormMethod.Post,new{enctype = "multipart/form-data"}))
{
<div class="Content-inner-pages">
<div class="TopHeading TopHeading2">
<h2>Assets</h2>
<a class="CreateBtn AssetsBtn" href="Javascript:void(0);" onclick="javascript:$('#hdnIsNew').val('1')">Add Asset</a>
<div class="clearfix"></div>
</div>
<input type="hidden" id="hdnIsNew" value="1" />
<input type="hidden" id="hdnRecId" />
<!-- Slide Popup panel -->
<div class="cd-panel from-right AddAssetForm">
<header class="cd-panel-header">
<h3>Add Asset</h3>
Close
</header>
<div class="cd-panel-container">
<div class="cd-panel-content">
<div class="form-horizontal form-details popup-box">
<div class="form-group">
<label class="col-md-5 control-label">
Asset Title
</label>
<div class="col-md-7">
<input type="text" id="txtTitle" name="txtTitle" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Description</label>
<div class="col-md-7">
<textarea id="txtDesc" class="form-control" cols="5" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Attachment</label>
<div class="col-md-7">
<input type="file" id="file" class="custom-file-input">
</div>
</div>
<div class="form-group">
<div class="col-md-7 col-md-offset-5">
<input type="submit" value="Save" name="actionType" class="btn-class btn-success">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-content Custom-DataTable">
<table id="AdministationAssets" class="table table-hover dt-responsive CustomDatable AdministationAssetsTable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width:5%;">Assets</th>
<th style="width:15%;">
#Html.DisplayNameFor(model =>model.Title)
</th>
<th style="width:50%;">
#Html.DisplayNameFor(model =>model.Description)
</th>
<th style="width:8%;">Options</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td></td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem =>item.Description)
</td>
<td>
#Html.ActionLink("Edit", "AddEditRecord", new{ id = item.ID }, new { #class = "ActionEdit AssetEdit", onclick ="javascript:GetEditDetails(" + item.ID + ");" })
#Html.ActionLink("Delete", "AssetDelete", new{ id = item.ID }, new { #class = "ActionDelete", onclick = "return confirm('Are You Sure delete this record?');", })
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
and below is my controller that what i want to call when click on save button but 'img' is coming as null and after searching in google i found that to add #using(Html.BeginForm()) but still it is coming as null
[HttpPost]
public ActionResult AssetsPage(Asset ast, HttpPostedFileBase file)
{
using (GenericUnitOfWork gc = new GenericUnitOfWork())
{
if (HttpContext.Request.Files.Count > 0)
{
ast.ContainerName = "reports";
ast.BlobName = HttpContext.Request.Files[0].FileName;
ast.BlobUrl = BlobUtilities.CreateBlob(ast.ContainerName, ast.BlobName, null, GetStream(HttpContext.Request.Files[0].FileName));
ast.FileName = HttpContext.Request.Files[0].FileName;
}
gc.GetRepoInstance<Asset>().Add(ast);
gc.SaveChanges();
}
return RedirectToAction("AssetsPage");
}
Not able to find the solution. Please help or give some reference if possible.
Asp.Net MVC default model binding works with name attribute, So add name="file" attribute with input type="file" as shown :-
<input type="file" name="file" id="file" class="custom-file-input">

mvc Get a value of element in different cshtml with jquery

I have a page ("mypage.cshtml") and two partial view page ( partial1.cshtml, partial2.cshtml )
when Im in mypage click a button and display a modal which call partial1 with #Html.Partial("patial1") in a modal(bootstrap modal). it consist of html. when I a click a button on this modal it calls another modal consist of partial2..
Here is the issue; When I load the page begining (in mypage ) I need to get the value of checkbox that standing in second modal, that is partial2.
During I view this modal I can get this value with this:
$("input[type='checkbox'][id='4']").val();
it gives me the value which I expect but at the begining(in mypage.cshtml) this returns "undefined" :S
I couldnt understand this stuation both of these modal located in mypage but why I cant get these elements values untill I reach them ?
here is view mypage:
<div id="stack1" class="modal fade" tabindex="-1" data-width="400">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<form id="formKaydet" method="post" action="../KurulusBilgileri/KurulusBilgileriniGuncelle">
<div class="row">
<div class="col-md-12">
#Html.Partial("KurulusBilgileriniGuncelle", Model)
</div>
<div class="modal-footer">
<input type="hidden" name="SANAYI_TIPI" id="input_id" />
<input type="hidden" name="SANAYI_TIPI_DIGER" id="input_sanayitipi" />
<button type="button" data-dismiss="modal" class="btn default">Geri</button>
<a class="btn orange" onclick="sanayitipleriKaydet()">Kaydet A</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="stack2" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
#Html.Partial("SanayiTipiSecim", Model.SanayitipiModel)
</div>
</div>
</div>
<div class="modal-footer">
#*<button type="button" data-dismiss="modal" class="btn">Close</button>
<button type="button" class="btn yellow">Ok</button>*#
</div>
</div>
</div>
</div>
and my second modal (SanayiTipiSecim)
<table class="table-full-width">
<thead>
<tr>
<th></th>
<th><strong>Sanayici Tipi</strong></th>
<th><strong>Açıklama</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(1)" id="1" value="Boya Sanayi">
</td>
<td>
Boya Sanayi
</td>
<td>
Boya üretimi yapan imalathaneler
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(2)" id="2" value="Enerji üretimi ve dağıtımı">
</td>
<td>
Enerji üretimi ve dağıtımı
</td>
<td>
Ör. Enerji üretim merkezleri, enerji ara istasyonları vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="3" onclick="javascript:sanayitipiTotextarea(3)" value="Elektrik ve Elektronik Mühendisliği">
</td>
<td>
Elektrik ve Elektronik Mühendisliği
</td>
<td>
Elektronik parçaların üretimi vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="4" onclick="javascript:sanayitipiTotextarea(4)" value="Genel Mühendislik, imalat ve montaj">
</td>
<td>
Genel Mühendislik, imalat ve montaj
</td>
<td>
Herhangi bir mühendislik aktivitesi, üretim veya montaj vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="5" onclick="javascript:sanayitipiTotextarea(5)" value="Gıda ve içecek">
</td>
<td>
Gıda ve içecek
</td>
<td>
Gıda, alkollü içki vb?
</td>
script blocks in first page:
<script src="~/Scripts/js/kurulusbilgileri.js"></script>
<script>
sanayitipleriKaydet = function () {
debugger
var data = new Object()
data.ISIM = $("input[name='ISIM']").val();
data.ADRES_METIN = $("input[name='ADRES_METIN']").val();
data.TELEFON = $("input[name='TELEFON']").val();
data.FAKS = $("input[name='FAKS']").val();
data.E_POSTA = $("input[name='E_POSTA']").val();
data.SORUMLU_ISIM = $("input[name='SORUMLU_ISIM']").val();
data.SORUMLU_SOYISIM = $("input[name='SORUMLU_SOYISIM']").val();
data.FAALIYET_ALANI = $("input[name='FAALIYET_ALANI']").val();
data.CEVRE_BILGI = $("input[name='CEVRE_BILGI']").val();
data.BELEDIYE_MUCAVIR_ALAN = $("input[name='BELEDIYE_MUCAVIR_ALAN']:checked").val();
debugger
data.OSB_YERLESIK = $("input[name='OSB_YERLESIK']:checked").val();
data.KIYI_TESISI = $("input[name='KIYI_TESISI']:checked").val();
data.VERSIYON = $("input[name='VERSIYON']:checked").val();
data.SANAYI_TIPI = window.localStorage.getItem("sanayitipiid");
window.localStorage.removeItem("sanayitipiid");
debugger
var jsondata = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: 'application/json',
url: "/KurulusBilgileri/KurulusBilgileriniGuncelle",
data: jsondata,
success: function (result) {
debugger
var jsondata = JSON.parse(result)
if (jsondata.Passed) {
debugger
$('#tdISIM').empty();
$('#tdISIM').append(data.ISIM);
$('#tdADRES_METIN').empty();
$('#tdADRES_METIN').append(jsondata.data.ADRES_METIN);
$('#tdTELEFON').empty();
$('#tdTELEFON').append(jsondata.data.TELEFON);
$('#tdFAKS').empty();
$('#tdFAKS').append(jsondata.data.FAKS);
$('#tdE_POSTA').empty();
$('#tdE_POSTA').append(jsondata.data.E_POSTA);
$('#tdSORUMLU_ISIM').empty();
$('#tdSORUMLU_ISIM').append(jsondata.data.SORUMLU_ISIM);
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').empty();
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').append(jsondata.data.SANAYI_TIPI);//sanayitipi id si...
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').empty();
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').append(jsondata.data.FAALIYET_ALANI);
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').empty();
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').append(jsondata.data.CEVRE_BILGI);
debugger
if (jsondata.data.BELEDIYE_MUCAVIR_ALAN == "1") {
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked', true);
}
else
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked',false);
if (jsondata.data.OSB_YERLESIK == "1") {
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked', true);
}
else
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked',false);
if (jsondata.data.KIYI_TESISI == "1") {
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked', true);
}
else
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked',false);
if (jsondata.data.VERSIYON == "1") {
$("#tdVERSIYON > input[name='radioVersion']").prop('checked', true);
}
else
$("#tdVERSIYON > input[name='radioVersion']").prop('checked',false);
}
},
error: function () {
alert("ajax process in error");
}
});
}
</script>
kurulusbilgileri.js:
$(function () {
$("#btnSanayiTipiKaydet").on('click', sanayitipleriKaydet)
});
sanayiTipiTextGetir = function (id)
{
var text = $('input[id=' + id + ']').val();
debugger;
return text;
}
sanayitipilistesinigoster = function () {
$("#stack2").show();
}
sanayitipiTotextarea = function (id) {
$("#divSanayiTipi").show(600, null);
var sanayitipi = $("#" + id).val();
window.localStorage.setItem("sanayitipiid", id);
$("#input_sanayitipi").val(sanayitipi);
$("#input_id").val(id);
$("#stack2").modal('toggle');
}
Since you load your partial trough a modal, I'm assuming that the actual loading is done using AJAX. This means that when you first load your HTML page (the initial one), the partial is not yet part of the DOM (might have not been requested from the server). This in turn means that you checkbox is also not part of the DOM, and therefore is returned as undefined.

Resources