I wanted to add search query name to header on my subpage so for example if someone will type John in search box the page that he/she receives is: Searching results for: John
Home Controller:
public ActionResult Search(string searching)
{
IEnumerable<Book> books = from t in Book.allBooks select t;
if (!String.IsNullOrEmpty(searching))
{
books = books.Where(a => a.Title.ToLower().Contains(searching.ToLower()));
}
return View(books.ToList());
}
_Layout.cshtml:
<li class="d-none d-lg-block justify-content-center" style="align-self: center; padding-right: 10px">
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
<i class="fas fa-search" aria-hidden="true" style="padding-right: 5px"> </i>
#Html.TextBox("searching")
<input type="submit" value="Search" />
}
</li>
Search.cshtml:
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#*#Html.TextBox("searching")
<input type="submit" value="Search" />*#
}
#if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</h2>
}
else
{
foreach (var item in Model)
{
<div class="col-12 col-md-6 col-lg-6 col-xl-3 align-items-center" style="margin-top: 10px; margin-bottom: 10px;">
<div class="col-md-12 d-flex justify-content-center">
<img src="~/Content/BookImages/#item.Image" class="img-thumbnail" style="height: 400px; width: 250px;" />
</div>
<div class="col-md-12 text-center">
<strong>#Html.ActionLink(item.Title, "Details", "Home", new { id = item.Id }, null)</strong>
</div>
<div class="col-md-12 text-center">
#item.WriterFirstName
</div>
<div class="col-md-12 text-center">
#item.WriterLastName
</div>
</div>
}
}
Thank you for your help
This could work for you:
public ActionResult Search(string searching)
{
IEnumerable<Book> books = from t in Book.allBooks select t;
if (!String.IsNullOrEmpty(searching))
{
books = books.Where(a => a.Title.ToLower().Contains(searching.ToLower()));
}
ViewBag.SearchTerm = searching;
return View(books.ToList());
}
And in your view:
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#*#Html.TextBox("searching")
<input type="submit" value="Search" />*#
}
#if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</h2>
}
else
{
<h2 style="margin-top: 30px">Search results for: #ViewBag.SearchTerm</h2>
foreach (var item in Model)
{
<div class="col-12 col-md-6 col-lg-6 col-xl-3 align-items-center" style="margin-top: 10px; margin-bottom: 10px;">
<div class="col-md-12 d-flex justify-content-center">
<img src="~/Content/BookImages/#item.Image" class="img-thumbnail" style="height: 400px; width: 250px;" />
</div>
<div class="col-md-12 text-center">
<strong>#Html.ActionLink(item.Title, "Details", "Home", new { id = item.Id }, null)</strong>
</div>
<div class="col-md-12 text-center">
#item.WriterFirstName
</div>
<div class="col-md-12 text-center">
#item.WriterLastName
</div>
</div>
}
}
Mind you, this is a quick and dirty solution. The proper one would be to create a ViewModel and add both books and the search term.
public class SearchBookViewModel {
public IEnumerable<Book> Books {get; set;}
public string SearchTerm {get; set;}
}
If you can't change the ViewModel then go with the ViewBag. The bad thing about the ViewBag, is that if someone changes the code in the controller, then you will only find out during runtime.
Related
I have an Index page like below and on button click I have some code to save data into database and then it goes on details page.
But I the code should go to the details page only after completing the database save operation; I want to show a loader image until then; how can I do this?
Currently I'm using begin post to post method and bind all model not using any ajax call. How can I show loader image and render before process complete to details page?
Index.cshtml
#model Dev.Models.DeviceReg
#using (Html.BeginForm("AddAsync", "Home", FormMethod.Post))
{
<div class="panel panel-primary">
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h4 id="aa">Name</h4>
<label>Select</label>
<table>
<tr>
<td>
#Html.DropDownListFor(m => m.Name, (SelectList)ViewBag.Name, "---Select Name---")
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-6">
<h4 id="aa">Model</h4>
<label>Select</label>
<table>
<tr>
<td>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewBag.TypeName, "---Select Type---")
</td>
</tr>
</table>
</div>
</div>
<div class="panel-footer" align="left">
<button type="submit" id="save" class="btn btn-success">
<span class="glyphicon glyphicon-arrow-right"></span> save
</button>
</div>
</div>
}
HomeController.cs
public async Task<ActionResult> AddAsync(DeviceReg deviceRegistration)
{
foreach (var deviceId in collection)
{
// save device information into database
Models.Device newDevice = new Models.Device()
{
Id = Guid.NewGuid(),
DeviceTypeId = deviceRegistration.DeviceType,
PlatformId = deviceRegistration.PlatformType,
DeviceId = deviceId,
};
_repository.InsertDevice(newDevice);
_repository.Save();
}
return View("Details", deviceRegistration);
}
Details.cshml
#model Dev.Models.DeviceReg
<body style="background-color:black">
<div class="panel panel-primary">
<div class="panel-heading" align="center">
<h2 class="panel-title">Details</h2>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h3><label>Current Data</label></h3>
<br />
</div>
</div>
<div class="row">
<div class="col-md-6">
<h4 id="aa">Name</h4>
<label>#Model.Name</label>
</div>
</div>
<div class="row">
<div class="col-md-6">
<h4 id="aa">Type</h4>
<label>#Model.TypeName</label>
</div>
</div>
<hr />
<br />
<label>Your process is running.</label>
<br />
<div class="row">
<div class="col-md-6">
<h3><label>Status</label></h3>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div style="clear: both">
<h2 style="float: left">10</h2>
<h6 style="float: right">Active Number</h6>
</div>
</div>
</div>
</div>
</div>
</body>
Well, if you need to show loader while post form is submitting, you can use javascript functions to show it, like
#using (Html.BeginForm("AddAsync", "Home", FormMethod.Post, new { onsubmit = "showLoader(this);" }))
{
...
}
plus JS
<script>
var showLoader = function(form){
$("<div />").css({
'position' : 'fixed',
'left' : 0,
'right' : 0,
'bottom' : 0,
'top' : 0,
'background' : '#0020ff36',
'z-index' : '99',
'text-align' : 'center'
}).appendTo($("body"))
.append(
$("<img />").attr("src", "https://mir-s3-cdn-cf.behance.net/project_modules/disp/35771931234507.564a1d2403b3a.gif")
);
}
</script>
or by jquery event, like
<script>
$("form").submit(function(){
//show loader
});
</script>
example of this code https://dotnetfiddle.net/gfEVSE
But, regarding to your clarification of the issue in comments, it's impossible to show Details page with progress of saving without Javascript or another additional requests.
Example without ajax but with aditional requests every N seconds
[HttpPost]
public ActionResult AddAsync(SampleViewModel deviceRegistration)
{
Task.Run(()=>
{
//Saving to DB
});
return RedirectToAction("Details", id = deviceRegistration.id);
}
public ActionResult Details(int id)
{
var isObjectExistInDb = checkIfExistInDb(id);
if (!isObjectExistInDb){
return View("ShowLoader", id);
}
return View(object);
}
where in ShowLoader.cshtml you need to reload page every N seconds.
With ajax it will be more clear, pretty code. Please, let me know, if you need example with ajax :)
I am currently learning Angular Js . I added the ADO.NET Entitly model in my project and Angular Js Packages as well. I am unable to do insert like user registration from my registration page. I lunch the developer tools and its showing following error ...
Module.js:5 Uncaught ReferenceError: angular is not defined
at Module.js:5
at Module.js:60
user.png Failed to load resource: the server responded with a status of 404 (Not Found)
load.png Failed to load resource: the server responded with a status of 404 (Not Found)
angular.min.js:42 Uncaught Error: [$injector:modulerr]
Here is my Code in Module.js file under MyScript Folder..
var app;
(function () {
var app = angular.module("myApp", []);
app.controller("Ctrl", ['$scope', function ($scope){
$scope.SaveUser = function () {
$("#divLoading").show();
var User = {
FName: $scope.fName,
LName: $scope.lName,
Email: $scope.uEmail,
Password: $scope.uPwd,
UserName: $scope.uName
};
var response = myService.AddUser(User);
response.then(function (data) {
if (data.data == "1") {
$("#divLoading").hide();
clearFields();
alert("User Created !");
window.location.href = "/Register/Login";
}
else if (data.data == "-1") {
$("#divLoading").hide();
alert("user alraedy present !");
}
else {
$("#divLoading").hide();
clearFields();
alert("Invalid data entered !");
}
});
}
function clearFields() {
$scope.fName = "";
$scope.lName = "";
$scope.Email = "";
$scope.Password = "";
$scope.UserName = "";
}
}]);
app.service("myService", function ($http) {
this.AddUser = function (User) {
var response = $http({
method: "post",
url: "/Register/AddUser",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
})
})();
Here is my code in controller.The name of my controller is RegisterController ..
public class RegisterController : Controller
{
public ActionResult Register()
{
return View();
}
//To check that user entered is already present or not.
public bool CheckUser(string user)
{
bool Exists = false;
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var uName = context.UserLogins.Where(x => x.UserName == user).ToList();
if (uName.Count != 0)
{
Exists = true;
}
}
return Exists;
}
//For saving the user details in database table.
public string AddUser(UserLogin usr)
{
if (usr != null)
{
if (CheckUser(usr.UserName) == false)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
UserLogin createUser = new UserLogin();
createUser.UserName = usr.UserName;
createUser.Firstname = usr.Firstname;
createUser.Lastname = usr.Lastname;
createUser.Email = usr.Email;
createUser.DateTimeCreated = DateTime.Now;
createUser.Password = Utility.Encryptpassword(usr.Password);
context.UserLogins.Add(createUser);
context.SaveChanges();
}
return "User created !";
}
else
{
return "User already present !";
}
}
else
{
return "Invalid Data !";
}
}
}
}
Here is HTML CODE ...
#{
Layout = null;
}
<html ng-app="myApp">
<head>
<title>Register</title>
<script src="~/Scripts/MyScript/Module.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container" ng-controller="myCntrl">
<br />
<div class="row">
<img src="~/Content/Images/user.png" /><h4>Register User</h4>
<hr />
<br />
<div class="col-md-6">
<form name="userForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
First Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Last Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de">
Email :
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Username :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Password :
</div>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-3">
<input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />
</div>
<div class="col-md-3">
#Html.ActionLink("Sign in", "Login", "Register", new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Here is Screen Shot when I run the application Click here ]1
Any one help me to solved this Error
remove the first var app;
It is like you are declaring the app twice, try this
var app = angular.module("myApp", [])
.controller('myCntrl',['$scope',function($scope){
// your code here
}])
.service();
UPDATE
In the Module.js, you have defined the name of your controller app.controller("Ctrl",), but in the html File when you're calling it, you wrote ng-controller='myCntrl'
You have to give them the same name, that's it
I have a form which has a DropDownList to select users and a form for user data. All controls are nested inside a form.
Cureently user DropDownList submits the form to notify about user selection to fetch appropriate data.
I want have a Button type(submit) which saves the data for the current user. Since both controls are in the same form and they both do submit, how can I differentiate if I am trying to select the user or saving the data in my action?
I have tried creating two forms as follows:
#model MyApp.Models.UserModel
#{
ViewBag.Title = "Profiles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" src="chosen.jquery.js"></script>
<script type="text/javascript" src="bootstrap-switch.js"></script>
<link rel="stylesheet" href="chosen.css" />
<link rel="stylesheet" href="bootstrap-switch.css" />
<style type="text/css">
.chosen-search{
display: none;
}
.form-group label{
margin-top: 10px;
}
.row{
margin-bottom: 20px;
}
th{
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#CurrentUserId').chosen({placeholder_text_single: "Select a user"});
$('#CurrentGroupId').chosen({placeholder_text_single: "Select a group"});
$('#CurrentRoleId').chosen({placeholder_text_single: "Select a role"});
$('#IsActive').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "ACTIVE",
offText: "PASSIVE",
animate: false,
handleWidth: 60
});
$('.authorizationCheckBox').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "Y",
offText: "N",
animate: false,
size: "mini"
});
});
</script>
#using (Html.BeginForm("Profile", "User"))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-3">
<div class="row">
<label class="control-label">Selected user :</label>
</div>
</div>
<div class="col-sm-9">
<div class="row">
#Html.DropDownListFor(x => x.CurrentUserId, new SelectList(Model.AllUsers, "Id", "Username"), "", new { #class = "form-control", onchange = #"this.form.submit();" })
</div>
</div>
</div>
}
#using (Html.BeginForm("SaveProfile", "User"))
{
if (!string.IsNullOrWhiteSpace(Model.CurrentUser))
{
<div class="row">
<div class="col-sm-3">
<div class="row">
#if (string.IsNullOrWhiteSpace(Model.UserImageUrl))
{
<img src="no-user.png" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-upload"></span> Upload avatar
</button>
}
else
{
<img src="#Model.UserImageUrl" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-retweet"></span> Change avatar
</button>
}
</div>
<div class="row">
<div class="input-group" style="margin: 0 auto;">
<div class="switch-button xlg showcase-switch-button">
#Html.CheckBoxFor(x => x.IsActive)
</div>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Username :</label>
<div class="col-sm-10">
<input id="CurrentUser" name="CurrentUser" class="form-control form-control-flat" value="#Model.CurrentUser" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">E-mail :</label>
<div class="col-sm-10">
<input id="EMail" name="EMail" class="form-control form-control-flat" value="#Model.EMail" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Membership :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentGroupId, new SelectList(Model.AllGroups, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Role :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentRoleId, new SelectList(Model.AllRoles, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<button id="btnSave" type="submit" class="btn btn-info" style="float: right; margin-right: 10px; margin-bottom: 40px;">
<span class="glyphicon glyphicon-trash"></span>Save changes
</button>
}
}
[HttpGet]
public ActionResult Profile()
{
return View(CreateInitialUserModel());
}
[HttpPost]
public ActionResult Profile(UserModel model)
{
model = GetUserModel(model.CurrentUserId.Value);
ModelState.Clear();
return View(model);
}
[HttpPost]
public ActionResult SaveProfile(UserModel model)
{
SaveModel(model)
return RedirectToAction("Profile");
}
But the problem is, at HttpPost of Profile action works well. But when I click the Save button and the HttpPost SaveProfile action is called, input parameter model does not have the values set on the screen.
I would actually use two forms. Not only does it relieve your problem here, as you can just add a hidden field or something to each form to indicate which was submitted, but it prevents other issues you're likely to run into, like failing validation on any required user fields in the create form, when you just select a user, because no data was submitted for those fields.
Short of that, just use whatever JavaScript you're already using to automatically submit when an option is selected from the drop down to change a value of a hidden field or otherwise modify the post data before it's submitted.
Why not use jquery for data retrieval? You could switch you dropdown to instead call a jquery function that performs an ajax call to a controller method that retrieves the relevant user data. Then, you can bind the data to the appropriate fields on the page using jquery. You would then only have one submit button on your view, handled through the normal mvc form process.
-in drop downdown list change event ,you should store UserID to a variable like global variable or hiddenfields.
-Create a Button
in function=
function submitvalues()
{
//get stored userID here from variable
//perform submit here
}
I have this model, Customer . When i get the information with an id, it works just fine.
Like ;
/Customer/Entity/5
#model ProgSpace.Models.Customer
#{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_MainLayout.cshtml";
}
#section bodypane
{
#using (Html.BeginForm("Entity", "Customer", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4>
</div>
<div class="clearfix"></div><br />
<div class="col-md-2">
<div class="col-md-12">
<div class="col-md-12 fileupload fileupload-exists" data-provides="fileupload">
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 200px; height: 150px;">
<img src="#Model.Picture.Path" />
</div>
<div>
<span class="btn btn-default btn-file">
<span class="fileupload-new">Add Pic </span>
<span class="fileupload-exists">Change</span><input name="file" id="file" type="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="col-md-10">
<div class="col-md-3">
<label>Name *</label>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Company</label>
#Html.TextBoxFor(model => model.Contact.Company, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Phone </label>
#Html.TextBoxFor(model => model.Contact.Phone, new { #class = "form-control" })
</div>
</div>
<div class="clearfix"><br /></div>
<p> </p>
<div class="col-md-12">
<div class="btn-group">
<button class="btn btn-danger btn-lg">Cancel</button>
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</div>
}
}
And in the controller i have these actions.
public ActionResult Entity(int id)
{
Customer cust= sis.Customers.Where(t => t.ID == id).FirstOrDefault();
return View(cust);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Entity(Customer cust, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
/* Do something */
}
else
{
}
return View(cust);
}
When the verb is GET , it's fine. But when i post this form and when the second action (HttpPost action) kicks in , view throws an error..
Object reference not set to an instance of an object
which marks the Model.ID is null in the view.
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4> ---> THIS HERE THROWS NULL EXCEPTION
</div>
I've tried to add a HiddenFor for the Model.ID like
#Html.HiddenFor(t => t.ID)
but it didn't change anything.
How do i get back to the same view with the same context again ?
I am trying post a simple list within a model back to the controller. its rendered correctly but on post its always empty. I noticed when I use #Html.Hidden for the id and name are different for instance id becomes TestExceptionDisplay_[0]__Exception and name becomes TestExceptionDisplay[0].Exception. So I use an input type and try to make the way it likes to render but it does not work. I tried partial view, editor templates, nothing seems to work. TestException Display is a very simple list of an object called public List<RunLogEntryTestExceptionDisplay> TestExceptionDisplay { get; set; }
public class RunLogEntryTestExceptionDisplay
{
public string Exception { get; set; }
}
Snippet in the view which uses a for loop to render list, list is rendered fine but on post TestExceptionDisplay is NULL always:
#if (Model.TestExceptionDisplay != null)
{
for (var i = 0; i < Model.TestExceptionDisplay.Count; i++)
{
<tr>
<td>
#Model.TestExceptionDisplay[i].Exception
#*#Html.HiddenFor(m => m.TestExceptionDisplay[i].Exception)*#
<input name="RunLogEntry.TestExceptionDisplay_[#i]__Exception" type="hidden" value="#Model.TestExceptionDisplay[i].Exception" />
</td>
</tr>
}
}
OR this does not even work with editor templates upon post
#if (Model.TestExceptionDisplay != null)
{
#Html.EditorFor(x => x.TestExceptionDisplay)
}
Editor Template in Shared\EditorTemplates with the exact name of RunLogEntryTestExceptionDisplay
#model RunLog.Domain.Entities.RunLogEntryTestExceptionDisplay
<div>
#Html.EditorFor(x => x.Exception)
#Html.HiddenFor(x => x.Exception)
</div>
Rendered HTML looks like below, I did not copy the entire list, PLEASE NOT THAT THE ID AND NAME SEEM TO RENDER IN A DIFFERENT NAMING CONVENTION. IT HAPPENS in both cases, if I use an editor template or a for loop. thanks
<input id="TestExceptionDisplay_9__Exception" name="TestExceptionDisplay[9].Exception" type="hidden" value=""1404 TestException - Parameters:Unable to calculate result, assay is not calibrated for Assay Number (135), Assay Version (5), Track (1), Lane (2), and Reagent Lot Number (26600LI06)"" />
Complete View:
#model RunLog.Domain.Entities.RunLogEntry
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/errorCode.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/testexception.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/runLogEntry.js")" type="text/javascript"></script>
<script type="text/javascript">
var runlogListErrorsUrl = '#Url.Action("ListErrorCodes", "RunLogEntry")';
</script>
<fieldset>
<legend>Enter a new Run Log Entry</legend>
#using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<div class="exception">#(ViewBag.ErrorMessage)</div>
<div class="bodyContent">
<span class="leftContent">Load List File (Select): </span><span class="rightContent">
<input type="file" name="file" id="file1" style="width: 500px" />
</span>
</div>
if (Model.LoadListStoredFileName != null)
{
<div class="bodyContent">
<span class="leftContent">Attached Load List: </span><span class="rightContent">
#Html.ActionLink(Model.LoadListFileName, "Download", new { #file = Model.LoadListStoredFileName })
</span>
</div>
}
<div class="bodyContent">
<span class="leftContent">Output File (Select): </span><span class="rightContent">
<input type="file" name="file" id="file2" style="width: 500px" />
</span>
</div>
if (Model.OutputStoredFileName != null)
{
<div class="bodyContent">
<span class="leftContent">Attached Output: </span><span class="rightContent">
#Html.ActionLink(Model.OutputFileName, "Download", new { #file = Model.OutputStoredFileName })
</span>
</div>
}
<div class="bodyContent">
<span class="leftContent">Import Files: </span>
<button name="submit" class="art-button" type="submit" value="Upload" style="width: 100px">
Upload</button>
<button name="submit" class="art-button" type="submit" value="Remove" style="width: 100px">
Remove</button>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Operator")
</span><span class="rightContent">
#Html.DropDownList("OperatorID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Run ID")
</span><span class="rightContent">[Generated] </span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Run Start Date / Time")
</span><span class="rightContent">
#Html.EditorFor(model => model.RunDate)
#Html.DropDownList("Hour", ListHelpers.HourList())
:
#Html.DropDownList("Minute", ListHelpers.Minute15List())
#Html.DropDownList("AMPM", ListHelpers.AMPMList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("System")
</span><span class="rightContent">
#Html.DropDownList("SystemID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Run Type")
</span><span class="rightContent">
#Html.DropDownList("RunTypeID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Run Description")
</span><span class="rightContent">
#Html.TextAreaFor(model => model.RunDescription, new { style = "width: 600px; height=30px" })
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Assay Performance Issues")
</span><span class="rightContent">
#Html.DropDownList("AssayPerformanceIssues1", ListHelpers.YesNoList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Tests/Cycles Requested")
</span><span class="rightContent">
#Html.EditorFor(model => model.SPTestsRequested)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Tests/Cycles Completed")
</span><span class="rightContent">
#Html.EditorFor(model => model.SPTestsCompleted)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Run Status")
</span><span class="rightContent">
#Html.DropDownList("RunStatusID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Assay")
</span><span class="rightContent">
#Html.ListBoxFor(model => model.SelectedAssayIDs, new MultiSelectList(RunLog.Domain.Lists.GlobalList.AssayListItems(), "ID", "Name", Model.SelectedAssayIDs))
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Error Code")
</span><span class="rightContent"><span id="ChildDialogLink" class="treeViewLink">Click
here to Select Error Codes</span>
<br />
<span id="ErrorCodeDisplay" style="cursor: pointer; text-decoration: underline;">#(Model.ErrorDescription)</span>
#Html.HiddenFor(model => model.ErrorDescription)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Test Exceptions")
</span><span class="rightContent"><span id="TestExceptionChildDialogLink" class="treeViewLink">
Click here to View Test Exceptions</span>
<br />
<span id="TestExceptionDisplayy"></span></span>
</div>
<div id="testExceptiontreeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
overflow: scroll; width: 800px; height: 450px;">
<div id="testExceptions">
</div>
<div id="inputTestExceptions">
<table class="grid" style="width: 450px; margin: 3px 3px 3px 3px;">
<thead>
<tr>
<th>
Exception String
</th>
<th>
Comment
</th>
</tr>
</thead>
#* #{var index = 0;}*#
#if (Model.TestExceptionDisplay != null)
{
for (var i = 0; i < Model.TestExceptionDisplay.Count; i++)
{
<tr>
<td>
#Model.TestExceptionDisplay[i].Exception
#Html.HiddenFor(m => m.TestExceptionDisplay[i].Exception)
</td>
</tr>
}
}
</table>
</div>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Service Entry Request")
</span><span class="rightContent">
#Html.DropDownList("ServiceRequest", ListHelpers.YesNoList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Problem Description")
</span><span class="rightContent">
#Html.TextArea("ProblemDescription", new { style = "width: 600px; height: 30px" })
</span>
</div>
<p>
<input id="LogType" type="hidden" value="Run" />
<input id="ID" type="hidden" value="0" />
#if (Model.ExitCode == "1")
{
#Html.Hidden("ExitCode", Model.ExitCode)
}
else
{
<input id="ExitCode" type="hidden" value='0' />
}
</p>
#Html.HiddenFor(model => model.MaxReplicateId)
#Html.HiddenFor(model => model.MinReplicateId)
#Html.HiddenFor(model => model.OutputFileName)
#Html.HiddenFor(model => model.OutputStoredFileName)
#Html.HiddenFor(model => model.LoadListFileName)
#Html.HiddenFor(model => model.LoadListStoredFileName)
#Html.HiddenFor(model => model.MinTestCompletionDate)
#Html.HiddenFor(model => model.MaxTestCompletionDate)
<div class="bodyContent">
<span class="leftContent"></span><span class="rightContent">
<button name="submit" class="art-button" type="submit" value="Create">
Create</button></span>
</div>
}
</fieldset>
<script src="#Url.Content("~/Scripts/exitCode.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/exitCode.js")" type="text/javascript"></script>
<div id="treeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
overflow: scroll; width: 800px; height: 450px;">
<div id="errorCodes">
#Html.RenderTree(CacheHelper.ErrorCodes(), ec => ec.Name, ec => ec.Children.ToList(), ec => (ec.ID).ToString(), null, "e")
</div>
<div id="inputReps" style="display: none;">
</div>
</div>
Why are you expecting the list in the model you receive to be populated?
The model on POST is populated only with data from the form - MVC creates a new instance of your model class and populates the fields it can match up.
Because of this, the stock way of making sure your lists are populated is to have a helper method which populates them. You can then call this from either the original Get or the Post method to repopulate the lists.
The only time you'd expect to get a list populated in your model by PMV on postback is when the details to rebuild the list are available in form elements.
It's possible I've missed it in your reams of code but I can't see you doing that anywhere.
You should initialize your list in your first method, then pass to post method.