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.
Related
I have an ASP.NET MVC project. The cshtml is as following:
<div class="container">
<div class="PublicInfo form-group">
<div class="dividerBar">
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-4">
<span class="lableName">From: </span>
</div>
<div class="col-lg-4 col-md-4 col-sm-8 col-xs-8">
#Html.TextBoxFor(m => m.StartTimeShamsi, new { #readonly = "readonly", #class = "pdate form-control input-sm", #id = "StartTimeShamsi", #style = "width: 85% !important" })
#Html.HiddenFor(m => m.StartTime, new { #id = "StartTime" })
</div>
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-4">
<span class="lableName">To: </span>
</div>
<div class="col-lg-4 col-md-4 col-sm-8 col-xs-8">
#Html.TextBoxFor(m => m.EndTimeShamsi, new { #readonly = "readonly", #class = "pdate form-control input-sm", id = "EndTimeShamsi", #style = "width: 85% !important" })
#Html.HiddenFor(m => m.EndTime, new { #id = "EndTime" })
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btn btn-primary btn-sm pull-right" type="button" onclick="btn_Search();">Search</button>
</div>
</div>
</div>
<div class="k-rtl col-lg-12 col-md-12 col-sm-12 col-xs-12 " id="KendoGrid">
#(Html.Kendo().Grid<SerialDestination>()
.Name("GridSerialDestination")
.Columns(columns =>
{
columns.Bound(o => o.SerialNo).Width(130).Filterable(filterable => filterable
.Extra(true)
.Operators(ops =>
ops.ForString(str => str.Clear()
.Contains("Contains")
.StartsWith("StartsWith")
.EndsWith("EndsWith")
.IsEqualTo("IsEqualTo"))));
})
.Selectable(s => s.Mode(GridSelectionMode.Single))
.Pageable()
.Sortable()
.Scrollable(builder => builder.Height("auto"))
.AutoBind(false)
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GridSerialDestination_ReadAll", "SerialDestinationRpt").Data("GridSerialDestination_GetParam"))
)
.Resizable(resize => resize.Columns(true))
)
</div>
</div>
When I push search button in the cshtml then the function btn_Search in the jquery will be called. In the jquery it must first read "grid.dataSource.read()" and wait for it to fill the kendo grid in the cshtml then after that the ajax must be called but it does not happen because as soon as the "grid.dataSource.read()" was read the ajax will be called
function btn_Search() {
var grid = $('#GridSerialDestination').data('kendoGrid');
grid.dataSource.read();
$.ajax({
url: '/SerialDestinationRpt/GetProcessCount',
data: { startDate: $("#StartTime").val(), endDate: $("#EndTime").val() },
type: "POST",
dataType: 'json',
async: true,
success: function (data) {
$('#pendingprocess').attr('data-count', data.AllSales);
$('#finishedprocess').attr('data-count', data.AllInstallation);
},
error: function (reponse) {
},
});
}
The backend function is as following:
public ActionResult GridSerialDestination_ReadAll([DataSourceRequest] DataSourceRequest request, string beginDate, string endDate)
{
var dt = SerialDestinationRptBAL.Sp_SerialDestinationRpt_ByDate(beginDate, endDate);
TempData["allSales"] = dt.Rows.Count;
TempData["allInstallation"] = dt.Select("ReceptionDate IS NOT NULL ").Count();
dt = PrepareData(dt);
return Json(dt.ToDataSourceResult(request));
}
[HttpPost]
public JsonResult GetProcessCount(string startDate, string endDate)
{
var allSales = TempData["allSales"]?.ToString();
var allInstallation = TempData["allInstallation"]?.ToString();
TempData["allSales"] = null;
TempData["allInstallation"] = null;
var model = new
{
AllSales = allSales,
AllInstallation = allInstallation
};
return Json(model, JsonRequestBehavior.AllowGet);
}
How can I solve the problem? Any help will be appriciated.
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a dropdownlist like this
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
it was like that because of this
<script type="text/javascript">
$(document).ready(function () {
$("#ddlGrade").change(function () {
var id = $(this).val();
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var select = $("#ddlSection");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Section"
}));
$.each(marksData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
and the JSON
public JsonResult PopulateDetails(string id)
{
List<Models.Section> a = new List<Models.Section>();
Models.ModelActions Ma = new ModelActions();
a = Ma.getSection(id);
var marksData = a.Select(c => new SelectListItem()
{
Text = c.sec_name,
Value = c.sec_id.ToString(),
});
return Json(marksData, JsonRequestBehavior.AllowGet);
}
now how can i add initial values to the dropdownlist in that format on postback? i need it for my search functionality. comments are much appreciated
EDITED:
VIEW:
<legend>CreateStudent</legend>
Full Name:
#Html.TextBox("searchTerm", null, new { id = "txtSearch" })
<input type="submit" value="search" name="submitbutton" />
<div class="editor-label">
#Html.LabelFor(model => model.si_id)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.si_id, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.si_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_fname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_fname)
#Html.ValidationMessageFor(model => model.si_fname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_mname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_mname)
#Html.ValidationMessageFor(model => model.si_mname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_lname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.si_lname)
#Html.ValidationMessageFor(model => model.si_lname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_gl_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_gl_id, new SelectList(Model.GradeLevel,"gl_id","gl_name"),"Select Grade Level", new { id = "ddlGrade" })
#Html.ValidationMessageFor(model => model.si_gl_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.si_sec_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.si_sec_id, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select a Section", new { id = "ddlSection" })
#Html.ValidationMessageFor(model => model.si_sec_id)
</div>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
</fieldset>
<p>
<input type="submit" value="Create" name="submitbutton" />
</p>
Controller
[HttpPost]
public ActionResult RegisterStudent(CreateStudent Create, string submitbutton, string searchTerm)
{
acgs_qm.Models.ModelActions Ma = new acgs_qm.Models.ModelActions();
List<CreateStudent> stud = new List<CreateStudent>();
switch (submitbutton)
{
case "search":
ModelState.Clear();
var model = new CreateStudent
{
GradeLevel = Ma.getGrade(),
//Guardian = Ma.getGuardian(),
si_id = Ma.getStringval(searchTerm,"si_id","student_info_tb","si_fullname"),
si_fname = Ma.getStringval(searchTerm, "si_fname", "student_info_tb", "si_fullname"),
si_mname = Ma.getStringval(searchTerm, "si_mname", "student_info_tb", "si_fullname"),
si_lname = Ma.getStringval(searchTerm, "si_lname", "student_info_tb", "si_fullname"),
si_gender = Ma.getStringval(searchTerm, "si_gender", "student_info_tb", "si_fullname"),
};
return View("RegisterStudent",model);
case "Create":
if (ModelState.IsValid)
{
Ma.insertStudent(Create);
}
Create.GradeLevel = Ma.getGrade();
Create.si_id = Ma.getcode("student_info_tb", "si_id", "1");
return View(Create);
default:
return View(Create);
}
}
Change your implementation as follows :
$.getJSON("../Employee/PopulateDetails", { id:id},
function (marksData) {
var $select = $("#ddlSection");
$select.empty();
$select.append('<option value=' + '0' + '>' + 'Select a Section' + '</option>');
$.each(marksData, function (index, itemData) {
$select.append('<option value=' + itemData.Value + '>' + itemData.Text + '</option>');
});
});
Try this
$("#ddlSection").change(function () {
var Id = this.value;
if (Id != 0) {
$.ajax({
type: "POST",
url: "/Employee/PopulateDetails",
data: JSON.stringify({ Id: Id }),
dataType: "text",
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
$("#ddlSection").empty();
$('#ddlSection').append("<option value='0'>Select Selection...</option>");
var yourArray = $.parseJSON(data);
if (yourArray != null) {
for (var i = 0; i < yourArray.length; i++) {
$('#ddlSection').append("<option value='" + yourArray[i].YourFiledName + "'>" + yourArray[i].YourFiledName + "</option>");
}
}
},
error: function (response) {
if (response != 1) {
alert("Error!!!!");
location.reload();
}
}
});
}
else {
alert("Please Select Any Value Name....");
}
});
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>