Related
I have a ajax.beginform that I have to upload a file and then in the view I have hidden for the path of the file that have been
saved in the server.
The problem is that the value of the path doesn't return to the view after the the post call.
I am returning new partial view with the errors and the value don't
coming
please help me
post method from controller that return partial view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
bool sociook = false;
socio.StudentId = sStudentId; // bind student id to socio model
socio = SocioDetValid(ref sociook,socio);
// add validation
if (ModelState.IsValid && sociook)
{
socio = SaveSocioModel(socio);
Response.StatusCode = 200;
}
else
Response.StatusCode = 300; // return error to client the model is not valid
return PartialView("~/Views/Student/Socio/SocioDetails.cshtml", socio); // return the partial view of the forn with validation messages
}
Sociodetvalid function that saves the file and add the path to path field:
// bank account validation and save
if (socio.FileBankAccount == null) // if there is no file
{
if (socio.PathBankAccount == null) // check if he upload file already - if not add error message
{
ModelState.AddModelError("FileBankAccount", "חובה לצרף קובץ");
ok = false;
}
}
else // upload new the file
socio.PathBankAccount = Files.SaveFileInServer(socio.FileBankAccount, "BankAccount", sStudentId, socio.PathBankAccount);
the section in view for upload and the hidden for the path string:
<div class="row">
<div class="col-xl-3 col-lg-3 col-md-4 col-12 ">
#Html.LabelFor(model => model.BankStatus, htmlAttributes: new { #class = "control-label col-12" })
#Html.EditorFor(model => model.BankStatus, new { htmlAttributes = new { #class = "form-control must m-1 mt-0" } })
#Html.ValidationMessageFor(model => model.BankStatus, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PathBankAccount)
</div>
<div class="col-xl-3 col-lg-3 col-md-4 col-12">
#Html.LabelFor(model => model.FileBankAccount, htmlAttributes: new { #class = "control-label col-12 must-sign", #for = "" })
<div class="chose-file m-1 mt-0">
#Html.TextBoxFor(model => model.FileBankAccount, new { #class = "form-control must", #type = "file", #accept = "image/jpeg,image/jpg,image/png,application/pdf", #style = "display:none;" })
<label for="FileBankAccount">
<i class="ml-1 material-icons">add_photo_alternate</i>
בחר קובץ
</label>
</div>
#Html.ValidationMessageFor(model => model.FileBankAccount, "", new { #class = "text-danger" })
</div>
#*
<div class="col-xl-3 col-lg-3 col-md-4 col-12" style="display:#(Model.PathBankAccount != null ? "" : "none")">
<label class="control-label col-12" for="">קובץ שמור</label>
<a name="#Model.PathBankAccount" class="btn btn-light btn-file m-1 mt-0">צפייה בקובץ שמור</a>
</div>*#
Thanks for help
Update:
Ajax form code : this is the part of the ajax that in a big view
<fieldset>
#using (Ajax.BeginForm("SaveSocioDetails", "Student", new AjaxOptions { HttpMethod = "POST", OnSuccess = "firstsuccess",OnFailure = "sociodetailsfail", UpdateTargetId="partialsocio" ,LoadingElementId = "div_loading" }, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="partialsocio">
#Html.Action("PartialSocioDetails", "Student", new { SpId = ViewBag.SpId })
</div>
<div id="div_loading" style="display:none;">
<img src="#Url.Content("~/Content/Pic/Spinner.gif")" alt="" />
</div>
<button class="btn btn-primary" type="submit">המשך</button>
}
<input type="button" name="next" class="next action-button bg-primary" hidden value="Next" id="sociodetnext" />
</fieldset>
this is the function of fail and success ajax:
<script>
$(document).ready(function ()
{
});
function firstsuccess() {
console.log('this is ajaxSuccess');
$("#sociodetnext").click();
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(bdata.responseText);
$('#partialsocio').html(bdata.responseText);
}
</script>
In the script that Have returned to the client the value of the string doesn't appear..
Thanks for help
Basic problem is I'm new to asp.net mvc, my problem is to I want to pass the values to another view and update my details.While clicking the update button, now I could pass the normal values. But unable to pass dropdown values. Also I couldn't update my (sql) database as well.
here is my code
1.index.cshtml
<table class="table">
<tr>
<th>
#Html.DisplayName("DepCode")
</th>
<th>
#Html.DisplayName("CourseCode")
</th>
<th>
#Html.DisplayName("SubjectCode")
</th>
<th>
#Html.DisplayNameFor(model => model.Room.RoomNo)
</th>
<th>
#Html.DisplayNameFor(model => model.date)
</th>
<th>
#Html.DisplayNameFor(model => model.Day)
</th>
<th>
#Html.DisplayNameFor(model => model.StartTime)
</th>
<th>
#Html.DisplayNameFor(model => model.FinishTime)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Department.Code)
</td>
<td>
#Html.DisplayFor(modelItem => item.Course.Code)
</td>
<td>
#Html.DisplayFor(modelItem => item.Subject.Code)
</td>
<td>
#Html.DisplayFor(modelItem => item.Room.RoomNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Day)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.FinishTime)
</td>
<td>
<input type="button" class="btn-primary btn-primary" title="Update" value="Update" onclick="location.href='#Url.Action("Edit", "AllocateClassRooms", new { id = item.Id })'" />
</td>
</tr>
}
</table>
2.AllocateClassRoomsController.cs
[HttpGet]
public ActionResult Edit(int ID)
{
using (UniversityDbContext db=new UniversityDbContext())
{
ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code");
ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code");
ViewBag.DepartmentId = db.Departments.ToList();
AllocateClassRoom allocateClassRoom = new AllocateClassRoom();
allocateClassRoom.DepartmentId = getAllocationDetails.DepartmentId;
allocateClassRoom.CourseId = getAllocationDetails.CourseId;
allocateClassRoom.SubjectID = getAllocationDetails.SubjectID;
allocateClassRoom.RoomId = getAllocationDetails.RoomId;
allocateClassRoom.date = getAllocationDetails.date;
allocateClassRoom.Day = getAllocationDetails.Day;
allocateClassRoom.From = getAllocationDetails.From;
allocateClassRoom.To = getAllocationDetails.To;
allocateClassRoom.StartTime = getAllocationDetails.StartTime;
allocateClassRoom.FinishTime = getAllocationDetails.FinishTime;
return View(allocateClassRoom);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AllocateClassRoom allocateClassRoom)
{
ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code", allocateClassRoom.CourseId);
ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code", allocateClassRoom.SubjectID);
ViewBag.DepartmentId = db.Departments.ToList();
ViewBag.RoomId = new SelectList(db.Rooms, "Id", "RoomNo", allocateClassRoom.RoomId);
allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
3.Edit.cshtml
#model UniversityMvcApp.Models.AllocateClassRoom
#if (Errormessage != null)
{
<label>#Errormessage</label>
}
#if (allocatedMessage != null)
{
<label>#allocatedMessage</label>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Department Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="DepartmentId" id="DepartmentId">
#foreach (var department in ViewBag.DepartmentId)
{
<option value="#department.ID">#department.Code</option>
}
</select>
#Html.ValidationMessageFor(model => model.CourseId)
</div>
</div>
<div class="form-group">
#Html.Label("Course Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="CourseId" id="CourseId"></select>
#Html.ValidationMessageFor(model => model.CourseId)
</div>
</div>
<div class="form-group">
#Html.Label("Subject Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="SubjectID" id="SubjectID"></select>
#Html.ValidationMessageFor(model => model.SubjectID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomId, "Lecture Place", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="RoomId" id="RoomId">
#foreach (var room in ViewBag.RoomId)
{
<option value="#room.Id">#room.RoomNo</option>
}
</select>
#Html.ValidationMessageFor(model => model.RoomId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.date, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.date, new { #id = "Date" })
#Html.ValidationMessageFor(model => model.date)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Day, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="Day" id="Day">
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thrusday">Thrusday</option>
<option value="Friday">Friday</option>
</select>
#Html.ValidationMessageFor(model => model.Day)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.From, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.From, new { #class = "From" })
#Html.ValidationMessageFor(model => model.From)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.To, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.To, new { #class = "To" })
#Html.ValidationMessageFor(model => model.To)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
$("#Date").datepicker({ dateFormat: 'dd-mm-yy' }).val;
});
$('.From,.To').timepicker({
timeFormat: 'h:mm p',
interval: 30,
minTime: '8',
maxTime: '6:00pm',
defaultTime: '8',
startTime: '8:00',
dynamic: false,
dropdown: true,
scrollbar: true
});
$(document).ready(function () {
$("#DepartmentId").change(function () {
var deptId = $("#DepartmentId").val();
$("#CourseId").empty();
$("#CourseId").append('<option value="">Select</option>');
var json = { DepartmentId: deptId };
$.ajax({
type: "POST",
url: '/AllocateClassRooms/GetCourseByDepartmentId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$("#CourseId").append('<option value="' + value.Id + '">'
+ value.Code + '</option>');
});
}
});
});
});
$(document).ready(function () {
$("#CourseId").change(function () {
var courId = $("#CourseId").val();
$("#SubjectID").empty();
$("#SubjectID").append('<option value="">Select</option>');
var json = { CourseId: courId };
$.ajax({
type: "POST",
url: '/AllocateClassRooms/GetSubjectByCourseId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$("#SubjectID").append('<option value="' + value.SubjectID + '">' + value.Code + '</option>');
});
}
});
});
});
</script>
}
</div>
4.my model is AllocateClassRoom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UniversityMvcApp.Models
{
public class AllocateClassRoom
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public int SubjectID { get; set; }
public Subject Subject { get; set; }
public int RoomId { get; set; }
public Room Room { get; set; }
public DateTime date { get; set; }
public string Day { get; set; }
public string From { get; set; }
public string To { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan FinishTime { get; set; }
}
}
I put most important code as well, if anyone help me,it will be helpful.
#Dilky
i caught your problem, according to your model, foreign key conflict will happen, that's why you couldn't get those values.try this code in your controller post method.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AllocateClassRoom allocateClassRoom)
{
string subID = Request.Form["SubjectID"].ToString();
var subject = db.Subjects.Where(s => s.Code == subID).FirstOrDefault();
int departmentID = Convert.ToInt32(subject.DepartmentId);
int CourseID = Convert.ToInt32(subject.SubCourForId);
int SubjectID = subject.SubjectID;
string roomNo = Request.Form["RoomId"].ToString();
var room = db.Rooms.Where(s => s.RoomNo == roomNo).FirstOrDefault();
int roomID = room.Id;
allocateClassRoom.DepartmentId = departmentID;
allocateClassRoom.CourseId = CourseID;
allocateClassRoom.SubjectID = SubjectID;
allocateClassRoom.RoomId = roomID;
allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Dilky
I think that using a Dropdownlist helper instead of creating the dropdown using a "for...each" statement could fix your problem.
Check out this link:
How to write a simple Html.DropDownListFor()?
Regards
follow this approach it will be helpful and workout for your case.
here is the link
Also,
inside your controller follow this code
[HttpGet]
public ActionResult Edit(int ID)
{
using (UniversityDbContext db=new UniversityDbContext())
{
ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code");
ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code");
ViewBag.DepartmentId = db.Departments.ToList();
AllocateClassRoom allocateClassRoom = new AllocateClassRoom();
allocateClassRoom.DepartmentId = getAllocationDetails.DepartmentId;
allocateClassRoom.CourseId = getAllocationDetails.CourseId;
allocateClassRoom.SubjectID = getAllocationDetails.SubjectID;
allocateClassRoom.RoomId = getAllocationDetails.RoomId;
allocateClassRoom.date = getAllocationDetails.date;
allocateClassRoom.Day = getAllocationDetails.Day;
allocateClassRoom.From = getAllocationDetails.From;
allocateClassRoom.To = getAllocationDetails.To;
allocateClassRoom.StartTime = getAllocationDetails.StartTime;
allocateClassRoom.FinishTime = getAllocationDetails.FinishTime;
var allocateClassRooms = db.AllocateClassRooms.Include(a => a.Course).Include(a => a.Department).Include(a => a.Subject).Include(a => a.Room).ToList();
var getAllocationDetails = db.AllocateClassRooms.Where(s => s.Id == ID).FirstOrDefault();
Department department = new Department();
var departmnt = db.Departments.Where(s => s.ID == getAllocationDetails.DepartmentId).FirstOrDefault();
ViewData["DepartmentData"] = departmnt.Code;
var course = db.Courses.Where(s => s.Id == getAllocationDetails.CourseId).FirstOrDefault();
ViewData["CourseData"] = course.Code;
var subject = db.Subjects.Where(s => s.SubjectID == getAllocationDetails.SubjectID).FirstOrDefault();
ViewData["subjectData"] = subject.Code;
var room = db.Rooms.Where(x => x.Id == getAllocationDetails.RoomId).FirstOrDefault();
ViewData["roomData"] = room.RoomNo;
ViewData["DayValue"] = getAllocationDetails.Day;
return View(allocateClassRoom);
}
}
as well as your edit.cshtml follow this code
#model UniversityMvcApp.Models.AllocateClassRoom
#if (Errormessage != null)
{
<label>#Errormessage</label>
}
#if (allocatedMessage != null)
{
<label>#allocatedMessage</label>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Department Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
var dep = ViewData["DepartmentData"];
var cou = ViewData["CourseData"];
var sub = ViewData["subjectData"];
var roo = ViewData["roomData"];
var day = ViewData["DayValue"];
}
<select name="DepartmentId" id="DepartmentId">
<option>#dep</option>
#foreach (var department in ViewBag.DepartmentId)
{
<option value="#department.ID">#department.Code</option>
}
</select>
#Html.ValidationMessageFor(model => model.CourseId)
</div>
</div>
<div class="form-group">
#Html.Label("Course Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="CourseId" id="CourseId"><option>#cou</option></select>
#Html.ValidationMessageFor(model => model.CourseId)
</div>
</div>
<div class="form-group">
#Html.Label("Subject Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="SubjectID" id="SubjectID"><option>#sub</option></select>
#Html.ValidationMessageFor(model => model.SubjectID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomId, "Lecture Place", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="RoomId" id="RoomId">
<option>#roo</option>
#foreach (var room in ViewBag.RoomId)
{
<option value="#room.Id">#room.RoomNo</option>
}
</select>
#Html.ValidationMessageFor(model => model.RoomId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.date, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.date, new { #id = "Date" })
#Html.ValidationMessageFor(model => model.date)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Day, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select name="Day" id="Day">
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thrusday">Thrusday</option>
<option value="Friday">Friday</option>
</select>
#Html.ValidationMessageFor(model => model.Day)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.From, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.From, new { #class = "From" })
#Html.ValidationMessageFor(model => model.From)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.To, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.To, new { #class = "To" })
#Html.ValidationMessageFor(model => model.To)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
<script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
$("#Date").datepicker({ dateFormat: 'dd-mm-yy' }).val;
});
$('.From,.To').timepicker({
timeFormat: 'h:mm p',
interval: 30,
minTime: '8',
maxTime: '6:00pm',
defaultTime: '8',
startTime: '8:00',
dynamic: false,
dropdown: true,
scrollbar: true
});
$(document).ready(function () {
$("#DepartmentId").change(function () {
var deptId = $("#DepartmentId").val();
$("#CourseId").empty();
$("#CourseId").append('<option value="">Select</option>');
var json = { DepartmentId: deptId };
$.ajax({
type: "POST",
url: '/AllocateClassRooms/GetCourseByDepartmentId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$("#CourseId").append('<option value="' + value.Id + '">'
+ value.Code + '</option>');
});
}
});
});
});
$(document).ready(function () {
$("#CourseId").change(function () {
var courId = $("#CourseId").val();
$("#SubjectID").empty();
$("#SubjectID").append('<option value="">Select</option>');
var json = { CourseId: courId };
$.ajax({
type: "POST",
url: '/AllocateClassRooms/GetSubjectByCourseId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
$.each(data, function (key, value) {
$("#SubjectID").append('<option value="' + value.SubjectID + '">' + value.Code + '</option>');
});
}
});
});
});
</script>
}
</div>
i think according to your code , it should workout for you
Form having dropdown country list when i click on submit button country ID value is passed to the controller..when i click on F10 keybord button country bind method is called .so again return to starting point so that again country value is Null Below i attached the screen shot:
<div class="page-content">
<div class="container-fluid">
<header class="section-header">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<h2>Company Registration Form</h2>
</div>
</div>
</div>
</header>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<section class="tabs-section">
<div class="tabs-section-nav tabs-section-nav-icons">
<div class="tbl">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="font-icon font-icon-cogwheel"></i>
Company Registration Form
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
<span class="nav-link-in">
<span class="glyphicon glyphicon-music"></span>
Company Social Network
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="fa fa-product-hunt"></i>
Company Reference
</span>
</a>
</li>
</ul>
</div>
</div><!--.tabs-section-nav-->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
<br />
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => Model.company.CompanyName, new { #class = "form-label semibold control-label" })
#Html.TextBoxFor(model => model.company.CompanyName, new { #class = "form-control", #id = "txtCompanyName", placeholder = "Enter the Company Name" })
#Html.ValidationMessageFor(model => model.company.CompanyName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.ShortName, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.ShortName, new { #class = "form-control", #id = "txtShortName", placeholder = "Enter the Short Name" })
#Html.ValidationMessageFor(model => model.company.ShortName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Division, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Division, new { #class = "form-control", #id = "txtDivision", placeholder = "Enter the Division" })
#Html.ValidationMessageFor(model => model.company.Division)
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Email, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Email, new { #class = "form-control", #id = "txtEmail", placeholder = "Enter your Email" })
#Html.ValidationMessageFor(model => model.company.Email)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Address1, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Address1, new { #class = "form-control", #id = "txtAddress1", placeholder = "Enter your Address Line 1" })
#Html.ValidationMessageFor(model => model.company.Address1)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Address2, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Address2, new { #class = "form-control", #id = "txtAddress2", placeholder = "Enter your Address Line 2" })
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Country, new { #class = "form-label semibold" })
#Html.DropDownList("Country", null, "--- Select Country ---", new { #class = "select2-arrow" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.State, new { #class = "form-label semibold" })
<select id="state" class="select2-arrow"></select>
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.City, new { #class = "form-label semibold" })
<select id="city" class="select2-arrow"></select><br />
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Pincode, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Pincode, new { #class = "form-control", #id = "txtPincode", placeholder = "Enter your Pincode" })
#Html.ValidationMessageFor(model => model.company.Pincode)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.CountryCode, new { #class = "form-label semibold" })
#*#Html.DropDownList("CountryCode", null, "---Select CountryCode---", new { #class = "select2-arrow" })*#
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.MobileNo, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.MobileNo, new { #class = "form-control", #id = "txtMobileNo", placeholder = "Enter your Mobile Number" })
#Html.ValidationMessageFor(model => model.company.MobileNo)
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.PhoneNo, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.PhoneNo, new { #class = "form-control", #id = "txtPhoneNo", placeholder = "Enter your PhoneNo" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.PanNo, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.PanNo, new { #class = "form-control", #id = "txtPanNo", placeholder = "Enter Company PanNo" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.TinNo, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.TinNo, new { #class = "form-control", #id = "txtTinNo", placeholder = "Enter Company TinNo" })
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.GSTno, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.GSTno, new { #class = "form-control", #id = "txtGSTno", placeholder = "Enter Company GSTno" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.IECCode, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.IECCode, new { #class = "form-control", #id = "txtIECCode", placeholder = "Enter Company IECCode" })
</fieldset>
</div>
</div><!--.row-->
<br />
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label semibold">Upload Company Logo</label>
<input type="file" name="file" id="txtUploadImage" style="cursor:pointer;" />
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label semibold">Perview Image</label>
<img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
<a id="remove" onclick="javascript:ClearFileUploadControl();" style="display: none; cursor: pointer;">Remove</a>
</fieldset>
</div>
</div>
<br />
<input type="submit" name="Submit" id="SaveCompany" value="Save" class="btn btn-rounded btn-inline btn-success" />
</div>
</section>
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.FaceBookID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { #class = "form-control", #id = "txtFaceBookID", placeholder = "Enter the Facebook Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.TwitterID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { #class = "form-control", #id = "txtTwitterID", placeholder = "Enter the Twitter Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.linkedinID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { #class = "form-control", #id = "txtlinkedinID", placeholder = "Enter the Linkedin Link" })
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step " />
<input type="submit" name="Submit" id="saveSocial" value="Next" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
Tab 3
<br />
<br />
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
</div><!--.tab-content-->
</section><!--.tabs-section-->
}
</div>
</div>
Scripts:
<script>
function GetInfo() {
var Company = {
CompanyName: $("#txtCompanyName").val(), ShortName: $("#txtShortName").val(), Division: $("#txtDivision").val(), Email: $("#txtEmail").val(), Address1: $("#txtAddress1").val(), Address2: $("#txtAddress2").val(), Country: $("#Country").val(), State: $("#state").val(), City: $("#city").val(),
Pincode: $("#txtPincode").val(), MobileNo: $("#txtMobileNo").val(), PhoneNo: $("#txtPhoneNo").val(), PanNo: $("#txtPanNo").val(), TinNo: $("#txtTinNo").val(), GSTno: $("#txtGSTno").val(), IECCode: $("#txtIECCode").val()
};
var mainModel = {};
mainModel.Company = Company;
$.ajax({
type: "POST",
url: "/Company/AddCompany",
data: JSON.stringify(mainModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
$(document).ready(function () {
$("#saveSocial").click(function (e) {
e.preventDefault();
GetInfo1();
});
$("#SaveCompany").click(function (e) {
//e.preventDefault();
GetInfo();
});
});
function GetInfo1() {
var Social = { FaceBookID: $("#txtFaceBookID").val(), TwitterID: $("#txtTwitterID").val(), linkedinID: $("#txtlinkedinID").val() };
var mainModel = {};
mainModel.CompanySocial = Social;
$.ajax({
type: "POST",
url: "/Company/AddSocial",
data: JSON.stringify(mainModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
</script>
<script>
$(document).ready(function () {
$("#Country").change(function () {
var id = $(this).val();
$("#state").empty();
$.get("State_Bind", { CountryID: id }, function (data) {
var v = "<option>--- Select State ---</option>";
$.each(data, function (i, v1) {
v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
});
$("#state").html(v);
});
});
$("#state").change(function () {
var id = $(this).val();
$("#city").empty();
$.get("City_Bind", { StateID: id }, function (data) {
var v = "<option>--- Select City---</option>";
$.each(data, function (i, v1) {
v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
});
$("#city").html(v);
});
});
});
</script>
Class value:
public int Country { get; set; }
public int State { get; set; }
public int City { get; set; }
Screen shot:
ActionResult:
[HttpPost]
public ActionResult AddCompany(MainModel mainModel)
{
try
{
Country_Bind();
if (ModelState.IsValid)
{
dp obj = new dp();
if (obj.AddNewCompany(mainModel))
{
ViewBag.Message = "Company added successfully";
}
}
return View();
}
catch
{
return View();
}
}
Country code:
public void Country_Bind()
{
DataSet ds = dblayer.Get_Country();
List<SelectListItem> coutrylist = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
coutrylist.Add(new SelectListItem { Text = dr["CountryName"].ToString(), Value = dr["CountryID"].ToString() });
}
ViewBag.Country = coutrylist;
}
You are currently calling the Country_Bind() method as the first statement inside your httppost action method. You actually need to do that when you want to rerender the dropdown list when re rendering the same view.
If you are not doing an ajax post,You should follow the PRG pattern. On successful save of the data, you should redirect to the GET action method which render the view. If the Modelstate validation fails, that is when you return the same view (so that you can show the validation message to user) and you need to repopulate the dropdown data before that.
When you do a Redirect, ViewData does not work to transfer messages.Use TempData instead.
[HttpPost]
public ActionResult AddCompany(MainModel mainModel)
{
try
{
if (ModelState.IsValid)
{
dp obj = new dp();
if (obj.AddNewCompany(mainModel))
{
TempData.Message = "Company added successfully";
return RedirectToAction("CompanyList");
}
}
// We need to repopulate the data needed for rendering dropdown
Country_Bind();
return View(mainModel);
}
catch(Exception ex)
{
// to do : Make sure to log the error
return View("Error");
}
}
In your case, when you do an ajax post returning a redirect result does not makes sense. You may return the url to the next page if needed as part of a json response and use that in your ajax calls success/done event handler and do appropriate things (redirect to the new page/show a message to user)
[HttpPost]
public ActionResult AddCompany(MainModel mainModel)
{
try
{
if (ModelState.IsValid)
{
dp obj = new dp();
if (obj.AddNewCompany(mainModel))
{
return Json(new { Message="Company added successfully"});
}
}
return Json(new { Message="Validation errors!"});
}
catch(Exception ex)
{
// must log the exception
return Json(new { Message="Error "});
}
}
Make sure to update your success/done event handler of your ajax call to read the response (the json and do something like showing message to user/hiding or showing the next tab)
I also noticed an issue with your ajaxifying code. Since you are making an ajax form submission, you should prevent the default form submit behavior by calling the event.preventDefault method.
$("#SaveCompany").click(function (e) {
e.preventDefault();
GetInfo();
});
I would also recommend to use a flat-lean view model specific for the view. So your properties will not be nested level and when you use the helper methods (TextBoxFor etx), It will generate the correct input field names and you do not need to manually build the Js object you want to send. You may simply use the jquery serialize() method on your form object and send that as the data for the ajax call.
I´m writing a project to manage a pool of users of asp.net identity 2.0, and i want to create a user and add roles to the user in the same view, so when i post the model just simple create the user and add the roles in the same action.
I don't know how to generate the roles list for the user, for example i have a dropdownlist for with the roles and id´s and my view is something like this
<div class="form-horizontal">
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading">Datos personales</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Nombre)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.Nombre, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Apellido)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.Apellido, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.DependenciaId)
</div>
<div class="col-md-8">
#Html.DropDownListFor(m => m.User.DependenciaId, new SelectList(ViewBag.ListaDependencia, "Id", "Descripcion"), "Ninguno", new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading">Datos usuario</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.UserName)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.NetUser)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.NetUser, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">Datos usuario</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Roles)
</div>
<div class="col-md-8">
#Html.DropDownListFor(m => m.User.Roles, new SelectList(ViewBag.RolesList, "Id", "Name"), "Ninguno", new { #class = "form-control" })
</div>
</div>
<table>
Here must present the roles to add to the user
</table>
</div>
</div>
I found a way
first a helper for offline collections, that a i found on internet
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
if (html.ViewData["ContainerPrefix"] != null)
{
collectionName = string.Concat(html.ViewData["ContainerPrefix"], ".", collectionName);
}
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
var itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
var htmlFieldPrefix = string.Format("{0}[{1}]", collectionName, itemIndex);
html.ViewData["ContainerPrefix"] = htmlFieldPrefix;
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex));
return BeginHtmlFieldPrefixScope(html, htmlFieldPrefix);
}
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)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
var 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 (var 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;
}
}
then using an editor template
<tr>
#using (Html.BeginCollectionItem("ListaObraSocialPrepagasSeleccionadas"))
{
<td>
<input type="radio" name="RolesUserTableRadio" />
#Html.HiddenFor(model => model.Id, new { #readonly = "readonly" })
</td>
<td>
#Html.HiddenFor(model => model.Id, new { #readonly = "readonly" })
#Html.DisplayTextFor(model => model.Name)
</td>
}
a partial view to manage the list
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddRoles").click(function () {
var rolId = $("#ddRoles").val();
if (rolId == null || rolId == '') {
alert("Debe seleccionar un rol.");
return;
}
var foundRol = $("#RolesUserTable").find("input[value='" + rolId + "']");
if (foundRol.size() > 0) {
alert("Ya se ha agregado el rol.");
return;
}
$.ajax({
url: '#Url.Action("AddRoles", "Users")',
data: {
rolId: rolId
},
type: 'GET',
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
if (data.Valid) {
$("#RolesUserTable").append(data.html);
} else {
alert('El rol seleccionado no existe');
}
},
error: function (jqXHR, exception) {
alert('Error durante la llamada al servidor.' + jqXHR.responseText);
},
complete: function () {
}
});
});
$("#btnDeleteRoles").click(function () {
var myRadio = $('input[name=RolesUserTableRadio]');
var radio = myRadio.filter(':checked');
if (radio.size() == 0) {
alert("Debe seleccionar un rol.");
return;
}
if (!confirm("¿Confirma que desea eliminar el rol seleccionado?")) {
return;
}
$(radio).closest('tr').remove();
});
});
</script>
<div style="width: 100%; overflow-x: auto;">
<table id="RolesUserTable" class="table table-striped">
<thead>
<tr>
<th></th>
<th>Rol</th>
</tr>
</thead>
#Html.EditorFor(m => m.Roles)
</table>
</div>
and finnaly the dropdown and the table
<div class="form-group">
<label for="ddRoles" class="col-sm-2 control-label">Roles</label>
<div class="col-sm-3">
#Html.DropDownList("ddRoles", new SelectList(ViewBag.Roleslist, "Id", "Name", null), "Seleccione un rol", new { #class = "selectpicker", data_live_search = "true" })
</div>
<div class="btn-group">
<button id="btnAddRoles" type="button" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span></button>
<button id="btnDeleteRoles" type="button" class="btn btn-default"><span class="glyphicon glyphicon-minus"></span> </button>
</div>
</div>
<div>
#Html.Partial("_Roles")
</div>
I am writing some javascript where the selected option in a dropdown menu get assigned to a hiddenfor value. This hiddenfor is using a model property (SelectedModule).
When I click my submit button, the model.SelectedModule has null value even though I assigned a value to it with my javascript.
View
#model UserManager.Models.vw_UserManager_Model
#{
ViewBag.Title = "EditUser";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div id="edit-user">
<fieldset>
<legend>Edit user details</legend>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.salutation, new List<SelectListItem>
{
new SelectListItem{ Text="Mr", Value = "Mr" },
new SelectListItem{ Text="Mrs", Value = "Mrs" },
new SelectListItem{ Text="Miss", Value = "Miss" },
new SelectListItem{ Text="Ms", Value = "Ms" },
new SelectListItem{ Text="Dr", Value = "Dr" }
})
#Html.ValidationMessageFor(model => Model.salutation)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.firstname)
#Html.ValidationMessageFor(model => model.firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.lastname)
#Html.ValidationMessageFor(model => model.lastname)
</div>
#{Html.Partial("~/Views/Partial/_AutocompleteGroupName.cshtml", this.ViewData);}
<div class="editor-label">
#Html.LabelFor(model => model.isactive)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.isactive)
#Html.ValidationMessageFor(model => Model.isactive)
</div>
<div class="editor-label">
#Html.Label("Is approved")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.IsApproved)
#Html.ValidationMessageFor(model => Model.IsApproved)
</div>
<div class="editor-label">
#Html.Label("Maximum concurrent users")
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.MaxConcurrentUsers)
#Html.ValidationMessageFor(model => Model.MaxConcurrentUsers)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.email)
#Html.ValidationMessageFor(model => model.email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.rowtype)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.rowtype, new { #readonly = "readonly", #id = "txtNonEditableRowType" })
- Non editable
</div>
<div class="editor-label">
#Html.Label("Current Module")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.module_name, new { #readonly = "readonly", #id = "txtNonEditableModule" })
- Non editable
#Html.ValidationMessageFor(model => model.module_name)
</div>
<br />
#if (Model.rowtype == "ALF")
{
<div id="alfModules">
#Html.Label("New module")
<br />
#{Html.RenderAction("_CreateUserModulesAlf", "UserManager");}
</div>
}
#if (Model.rowtype == "BRAD")
{
<div id="bradModules">
#Html.Label("New module")
<br />
#{Html.RenderAction("_CreateUserModulesBrad", "UserManager");}
</div>
}
<div class="editor-label">
#Html.LabelFor(model => model.group_name)
</div>
#* <div class="editor-field">
#Html.EditorFor(model => model.group_name)
#Html.ValidationMessageFor(model => model.group_name)
</div>*#
<div class="editor-label">
#Html.Label("Current Group")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.group_name, new { #readonly = "readonly", #id = "txtNonEditableGroup" })
- Non editable
#Html.ValidationMessageFor(model => model.group_name)
</div>
#Html.HiddenFor(model => Model.selected_module, new { id = "hdnSelectedModule" })
#* #Html.HiddenFor(model => Model.selected_moduleAlf, new { id = "hdnSelectedModuleAlf" })
#Html.HiddenFor(model => Model.selected_moduleBrad, new { id = "hdnSelectedModuleBrad" })*#
<br />
<fieldset style="width: 400px; padding-left: 15px;">
<legend>Group Checker</legend>
<div id="createuser-groupnamesearch">
#{Html.RenderAction("_txtGroupSearchForm", "UserManager");}
</div>
</fieldset>
<p>
<input type="submit" value="Edit" onclick="newModule()" />
</p>
<br />
#Html.ActionLink("Back to User Manager Dashboard", "Index")
</fieldset>
</div>
}
<script type="text/javascript">
$("#group_name").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("LookUpGroupName", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: request.term
},
success: function (data) {
response($.map(data, function (item) {
// alert(item.group);
return {
label: item.group,
value: item.group
} // end of return
})); // end of response
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
},
minLength: 2,
select: function (event, ui) { // Assign to hidden values to trigger onchange ajax call.
$.ajax({
url: '#Url.Action("GroupnameCheck", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: ui.item.label
},
success: function (data) {
$.each(data, function (index, value) {
if (index == "AlfGroup") {
$("#txtGroupnameExistsAlf").val(value);
if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
$("#txtGroupnameExistsAlf").css("background-color", "red");
}
else {
$('#txtGroupnameExistsAlf').css("background-color", "#33ff00");
}
}
if (index == "BradGroup") {
$("#txtGroupnameExistsBrad").val(value);
if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
$("#txtGroupnameExistsBrad").css("background-color", "red");
}
else {
$('#txtGroupnameExistsBrad').css("background-color", "#33ff00");
}
}
});
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
$('#hdnGroupAlf').val(ui.item.label);
$('#hdnGroupBrad').val(ui.item.label);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
function chkSelection() {
var rowType = $("#txtNonEditableRowType").val();
if (rowType == "ALF") {
var selectedVal = $("#ddlSelectedAlf option:selected").val();
$('#hdnSelectedModule').val(selectedVal);
}
else {
var selectedVal = $("#ddlSelectedBrad option:selected").val();
$('#hdnSelectedModule').text(selectedVal);
alert(selectedVal);
}
}
$(document).ready(function () {
// Non editable fields grey
$("#txtNonEditableGroup").css("background-color", "gray");
$("#txtNonEditableModule").css("background-color", "gray");
$("#txtNonEditableRowType").css("background-color", "gray");
// Show/Hide group check part based on IF ALF or BRAD
var rowType = $("#txtNonEditableRowType").val();
if (rowType == "ALF") {
$("#groupname-checker-alf").show();
$("#groupname-checker-brad").hide();
var selectedVal = $("txtNonEditableRowType").val();
$('#hdnModuleAlf').val(selectedVal);
}
else {
$("#groupname-checker-alf").hide();
$("#groupname-checker-brad").show();
var selectedVal = $("txtNonEditableRowType").val();
$('#hdnModuleBrad').val(selectedVal);
}
});
function newModule() { // Assign new selected module from dropdown to hidden form
// so it can be used in model as selected_module
if ($("#txtNonEditableRowType").val() == "ALF") {
var val = $("#module_name :selected").val();
$("#hdnSelectedModule").val(val);
}
else {
var val = $("#module_name :selected").val();
$("#hdnSelectedModule").val(val);
}
}
</script>
Controller
[HttpPost]
public ActionResult EditUser(vw_UserManager_Model model)
{
List<UserManager.Models.vw_UserManager_Model> modellist = new List<vw_UserManager_Model>();
int outcome = 0;
if (ModelState.IsValid)
{
outcome = UserManager.DAL.EditUser(model);
modellist.Add(model);
}
if (outcome == 1)
{
if (modellist.FirstOrDefault().rowtype == "Alf")
{
}
else
{
}
return RedirectToAction("showSuccessUser", new
{
CrudType = "Edit",
UserName = modellist.FirstOrDefault().UserName,
Password = modellist.FirstOrDefault().password,
FirstName = modellist.FirstOrDefault().firstname,
LastName = modellist.FirstOrDefault().lastname,
Email = modellist.FirstOrDefault().email,
GroupName = modellist.FirstOrDefault().group_name,
IsActive = modellist.FirstOrDefault().isactive,
selected_module = modellist.FirstOrDefault().module_name
});
}
else
{
ViewBag.Message = "Failure";
return RedirectToAction("showError", model);
}
}
Summary
When an item is selected in the drop down menu, the value is assigned to HiddenFor field. This works from using firebug I can see the value.
The problem is when I submit the form, the model.SelectedModule property in my C# code has a null value.
Does anyone know why?
I don't know if this is the problem but in one of your cases you are doing:
$('#hdnSelectedModule').text(selectedVal);
which should be:
$('#hdnSelectedModule').val(selectedVal);
Also since you are already using FireBug, inspect the AJAX request in the Net tab. You will see all the key/value pairs that are sent to the server and will be able to more easily identify the problem. For example is there a SelectedModule=some_value in the request? If so, assuming that your model has a property called SelectedModule and is of simple type (such as string) you will be able to get its value.