I have three dropdowns in my form, and I would like to not lose the data that the user has selected, even if I refresh or I navigate in other page and come back.
This is my view where I have the 3 dropdowns:
#using (Ajax.BeginForm("SearchForCars", "Home", null, new AjaxOptions { UpdateTargetId = "DivCategoriesTree", OnSuccess = "success", HttpMethod = "Post" }, new { make = "makes" }))
{
<div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<i class="fa fa-car" style="font-size:60px;color:red; padding-left:20px;"></i>
<strong style="padding-left:20px;">Vă rugăm să selectați vehiculul dumneavoastră!</strong>
</div>
<div class="col-sm-4">
<div style="padding-top:15px;">
<form class="form-control-static">
<div class="form-group">
<div class="row">
<div class="col-sm-10">
#if (ViewData.ContainsKey("makes"))
{
#Html.DropDownList("makes", ViewData["makes"] as List<SelectListItem>, "--Select car--", new { #class = "dropdown-toggle form-control" })
}
</div>
</div>
<div class="row">
<div class="col-sm-10">
<p></p>
#Html.DropDownList("models", new SelectList(string.Empty, "Value", "Text"), "--Select model--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
<div class="row">
<p></p>
<div class="col-sm-10">
#Html.DropDownList("engines", new SelectList(string.Empty, "Value", "Text"), "--Select engine--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<input type="submit" id="btnSearch" class="btn btn-default active" value="Cauta" disabled="disabled" style="width:150px;" />
</div>
</div>
}
</div>
Here are the 3 dropdowns:
I use cookies to store the data that the user has selected.
I tried to set the dropdown from the controller in this way:
public ActionResult Index()
{
var asa = HttpContext.Request.Cookies.Get("make_model_engine");
var model = asa.Values["model"].ToString();
var make = asa.Values["make"].ToString();
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name");
ViewData["makes"] = makeList;
**var selected = makeList.Where(x => x.Value == make).First();
selected.Selected = true;**
return View();
}
Although it seems that the selected value is set correctly from cookies, it does not work, the dropdowns are not showing the selected value.
I guess that I should fix this in the view with javascript, but I'm new to javascript and I don't know what would be the best fix for this.
Can you please help me how can I resolve this?
Thank you!
You can pass the selected value you read from the cookie as the last parameter of the SelectList constructor:
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name", make);
Related
I am trying to passed the value from the MVC form to JavaScript. I am using bootstrap to hide and show field. when I remove the bootstrap hide and show functionality on the form I will get the value in the message box but when the Hide/Show is enable I cannot get the value as shown by the image below. can anyowne tell me where I am going wrong
HTML
#using (Html.BeginForm("SearchPatient","HOME", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Search Criteria", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SearchCriteria,
new List<SelectListItem> {
new SelectListItem { Value = "" , Text = "Select Search Criteria" },
new SelectListItem { Value = "1" , Text = "Patient Id" },
}, new { #class = "form-control selectchosen" })
</div>
</div>
<div class="form-group" id="PatientId" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PatientId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientId, new { htmlAttributes = new { #class = "form-control " } })
</div>
</div>
</div>
<div class="form-group" id="AllShow" style="display:none">
<div class="form-group">
<div class="col-lg-offset-2">
<input type="button" value="Search" class="btn btn-success" id="btnSubmit" onclick="Enablecontrols();" />
</div>
</div>
</div>
</div>
}
JavaScript
<script type="text/javascript">
$('#SearchCriteria').change(function () {
if ($("#SearchCriteria").val() == 1) {
$("#AllShow").show();
$("#PatientId").show();
ValidateField("PatientId", true);
}
function Enablecontrols() {
$(document).ready(function () {
var patientid = $("#PatientId").val();
if ($("#SearchCriteria").val() == 1) {
alert("I am an alert box! the patient number is" + patientid);
}
}
}
</script>
rather than use the show/hide methods of bootstrap, use toggle. It's more reliable.
If that doesn't work you can also use $('#PatientId').css('display','block');
Issue fixed by changing the ID of the Div to dPatientId
Stupid mistake
I have been trying to send data to a controller using ajax but it redirects me to another url instead of posting data into the controller.
#section CustomScripts
{
<script type="text/javascript">
function save() {
var BookingDetails =
{
VehicleModel: document.getElementById('VehicleModel').value,
VehicleRegNo: document.getElementById('VehicleRegNo').value,
AppointmentTime: '1',
CustomerName: document.getElementById('CustomerName').value,
ContactNo: document.getElementById('ContactNo').value
}
var bd = JSON.stringify(BookingDetails);
$.ajax
({
url: '#Url.Action("Appointment", "AddAppointment")',
type: 'POST',
contentType: "application/json; charset= utf-8",
data: bd,
dataType: 'json',
success: function (results) {
#*window.location = '#Url.Action("Appointment", "AddAppointment")';*#
}
});
}
</script>
}
Controller:
[HttpPost]
public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)
{
BookingsRepository BookingRep = new BookingsRepository();
int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage);
if (ReturnRowsCount > 0)
{
//ShowMessage(MessageBox.Success, OperationType.Saved, ReturnMessage);
ViewBag.Message = ReturnMessage;
return RedirectToAction("AddAppointment", "Appointment");
}
else
{
ShowMessage(MessageBox.Error, OperationType.Error, ReturnMessage);
}
return View(AddBookingVM);
}
I have using a input with type submit which is calling save(); on onclick event.
<input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>
Here is the full view code:
#model ZahidCarWash.ViewModels.AddBookingsViewModel
#{
ViewBag.Title = "Add Appointment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- page banner -->
<div id="page-banner" class="page-banner-main" style="background-image: url('Content/images/bg/page-banner.jpg')">
<div class="container">
<div class="page-banner-block">
<div class="section">
<h3 class="section-heading">Appointments</h3>
</div>
<ol class="breadcrumb">
<li>Home</li>
<li>Page</li>
<li class="active"><a>Appointments</a></li>
</ol>
</div>
</div>
</div>
<!-- end page banner -->
#*#using (Html.BeginForm("AddAppointment", "Appointment", FormMethod.Post, new { enctype = "multipart/form-data" }))
{*#
<!-- appointments -->
<div id="appointments" class="appointment-main-block appointment-two-main-block">
<div class="container">
<div class="row">
<div class="section text-center">
<h3 class="section-heading text-center">Get an Appointment</h3>
#*<p class="sub-heading text-center">Etiam imperdiet imperdiet orci nunc nec neque phasellus leo dolor tempus non auctor.</p>*#
</div>
<div class="col-md-4 hidden-sm">
<div class="appointment-img">
<img src="~/Content/images/appointment.jpg" class="img-responsive" alt="Appointment">
</div>
</div>
<div class="col-md-8 col-sm-12">
<div class="appointment-block">
<form id="appointment-form" class="appointment-form" method="post" action="https://mediacity.co.in/autoplus/car-wash/version1/appointment.php">
<h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
<div class="row">
<div class="col-sm-4">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
new { #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Model" } } )
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Reg No." } })
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">2.</span>Available Timings</h5>
<div class="row">
#*<div class="col-sm-6">
<input type="text" class="form-control date-pick" id="appointment-date" name="appointment-date" placeholder="Appointment Date" required>
</div>*#
<div class="col-sm-6">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_TimeSlotID, new SelectList(ZahidCarWash.DAL.TimeSlotsRepository.getTimeSlots(), "TimeSlotID", "FromTo"), new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.fk_TimeSlotID, "", new { #class = "ErrorMessages" })
</div>
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">3.</span>Contact Details</h5>
<div class="row">
<div class="col-sm-4">
#Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { #class = "form-control", placeholder = "Customer Name" } })
#Html.ValidationMessageFor(Model => Model.CustomerName, "", new { #class = "ErrorMessages" })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Contact Number." } })
#Html.ValidationMessageFor(Model => Model.ContactNo, "", new { #class = "ErrorMessages" })
</div>
#*<div class="col-sm-12">
<textarea id="message" name="message" rows="6" placeholder="Message"></textarea>
</div>*#
</div>
<input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>
</form>
</div>
</div>
</div>
</div>
</div>
As discussed, change the type of your button to be a "button". Remove the onclick attribute and add an "id". We'll use this id to capture the button click.
<input type="button" id="btnSubmit" class="btn btn-default pull-right" value="Book Now"/>
Change the form declaration to the below. Looks like you have it commented out!
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmMyForm" }))
{
//HTML here
}
Capture the click in Jquery, serialize the form and post the form to the controller.
$(document).on("click", "#btnSubmit", function () {
var data = $("#frmMyForm").serialize();
$.ajax({
async: true,
type: "POST",
data: data,
url: "/Appointment/AddAppointment/",
success: function () {
//Do stuff here if needed
},
complete: function () {
//Stuff here if needed
}
});
});
Hope that helps you on your way,
You have url: '#Url.Action("Appointment", "AddAppointment")', but your Controller Action name is: public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)
(updated)
But you also have a RedirectToAction in your Action for the $.ajax - the $.ajax should have a response.
Try just sending a HttpPost transaction by changing your script to this:
function save() {
var BookingDetails =
{
VehicleModel: document.getElementById('VehicleModel').value,
VehicleRegNo: document.getElementById('VehicleRegNo').value,
AppointmentTime: '1',
CustomerName: document.getElementById('CustomerName').value,
ContactNo: document.getElementById('ContactNo').value
}
var form = document.createElement("form");
var url = '#Url.Action("Appointment", "AddAppointment")';
form.setAttribute("method", "POST");
form.setAttribute("action", url);
for (var key in BookingDetails) {
if (data.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", data[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
form.remove();
}
This is a straight HttpPost with no return expected in the script. It creates a form, attaches the data (by creating hidden inputs) to be sent to the action, adds the form to the DOM, submits and then removes it.
So I am trying to return a value from a text box as the parameter to another controller action that returns another partial. I think it would easier to just post some sample code rather than trying to explain what I am trying to do, so here is some sample code:
CSHTML:
<div class="row">
<div class="pt-sm-30 pb-xs-30 has-50px-footer">
<div class="col-lg-offset-1 col-lg-10">
<h3>CREATE A NEW PERSON PROFILE</h3>
<form class="form-spacers">
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label class="input-label" for="functionalRole">First Name <span class="ReqField">*</span></label>
#Html.TextBoxFor(model => model.Person.FirstName, new { #class = "form-control input-sm", #id = "firstName", #type = "text" })
</div>
<div class="col-md-6">
<label class="input-label" for="functionalRole">Last Name <span class="ReqField">*</span></label>
#Html.TextBoxFor(model => model.Person.LastName, new { #class = "form-control input-sm", #id = "lastName", #type = "text" })
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-md-9 col-lg-10 new-profile-footer">
<div class="col-lg-offset-1 col-lg-5 col-md-4 hidden-sm hidden-xs" style="margin-top: 16px;">
</div>
<div class="col-lg-6 col-md-8 col-sm-12" style="margin-top: 10px; text-align: right;">
<div class="row" style="white-space: nowrap;">
<button class="btn btn-primary button-blue btn-xs-110" onclick="location.href='#Url.Action("Index", "DirectoryMaintainer")'"><i class="fa fa-times-circle-o icon-xs-hidden" aria-hidden="true" style="padding-right: 5px;"></i>CANCEL</button>
<button id="continue" type="button" class="btn btn-success button-green btn-xs-110">CONTINUE<i class="fa fa-caret-right icon-xs-hidden" style="padding-left: 5px;" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
<script>
$("#continue").click(function () {
$("#partialViewDiv").load('#(Url.Action("RecordsMatch", "DirectoryMaintainer", new { #firstName = getFirstName(), #lastName = getLastName()}, Request.Url.Scheme))');
});
function getFirstName() {
return document.getElementById("firstName").value;
}
function getLastName() {
return document.getElementById("lastName").value;
}
</script>
Controller:
public PartialViewResult RecordsMatch(string firstName, string lastName)
{
//Do some logic with parameters here
return PartialView("_RecordsMatch");
}
So the issue I am having this that the line
$("#partialViewDiv").load('#(Url.Action("RecordsMatch", "DirectoryMaintainer", new { #firstName = getFirstName(), #lastName = getLastName()}, Request.Url.Scheme))');
is giving me an error on getFirstName() and getLastName(). The error is "The name getFirstName() does not exist in the current context". I am pretty new to MVC so I'm not sure if this is even possible or if there is a better way of doing it. If there is, then I am more than happy to learn it. Any and all suggestions would be greatly appreciated.
You cannot mix c# and js like that as the Url.Action gets executed in the server before your js code
Basically any C# code in your razor view gets executed by the razor view engine in the server and output of that (which is HTML/plain text) will be send to the browser. All your javascript code gets executed in the browser.
You can use Url.Action to generate the base url (without route value parameters) and add query strings to that at client side later.
$(function(){
$("#continue").click(function () {
var url='#Url.Action("RecordsMatch", "DirectoryMaintainer")';
url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();
$("#partialViewDiv").load(url);
});
});
When razor executes this code, it will render output like this (you can check the page view source and see this)
$(function(){
$("#continue").click(function () {
var url='/DirectoryMaintainer/RecordsMatch';
url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();
$("#partialViewDiv").load(url);
});
});
I want to disable or hide a PartialView based on values inside two different ILists. Both of these lists are stored in two Session variables, _UserRoleList and _PartialRoleList.
The list contents of _UserRoleList are of type User which contains the following properties:
UserName
RoleID
RoleDescription
SID
The list contents of _PartialRoleList are of type PartialRole which contains the following properties:
PartialName
RoleID
AccessLevelID
AccessLevelDescription
Case 1 - Disable all input controls inside the Partial View:
Disable ALL input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") if a RoleID of 3 is found in both session lists.
Case 2 - Set all input controls to read-only inside the Partial View:
All input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") should have their read-only attribute set to true if aRoleID of 2 is found in both session lists.
Question:
Would it be better to retrieve the two lists and then use a jQuery .each to loop through and search for equality on the RoleID fields? Would another option be to use Razor? If pseudo code could be provided, that would be a great help.
Controller snippet:
public ViewResult Index() /* Master View, starting point of application */
{
int userID;
IList<User> userRoleList;
IList<PartialRole> partialRoleList;
WindowsIdentity identity = null;
identity = WindowsIdentity.GetCurrent();
userRoleList = _homeService.GetUserDetails(identity.User.ToString());
userID = userRoleList.First().ID;
partialRoleList = _homeService.GetPartialDetails(userID);
if (Session["_UserRoleList"] == null)
{
HttpContext.Session.Contents.Add("_UserRoleList", userRoleList);
}
if (Session["_PartialRoleList"] == null)
{
HttpContext.Session.Contents.Add("_PartialRoleList", partialRoleList);
}
return View();
}
Original View - ClientDetails.cshtml:
#using InvoiceManagement.Models
#model InvoiceClient
#{
InvoiceCreditNoteViewModel viewModel = new InvoiceCreditNoteViewModel();
viewModel.Client = Model;
ViewBag.Title = "Client Details";
List<User> userRoleList = Session["_UserRoleList"] != null ? (List<User>)Session["_UserRoleList"] : null;
List<PartialRole> partialRoleList = Session["_PartialRoleList"] != null ? (List<PartialRole>)Session["_PartialRoleList"] : null;
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('input[type=radio][name=optionInvoiceCreditNote]').change(function () {
if (this.value == 'invoice') {
$("#InvoiceGrid").show();
$("#CreditNoteGrid").hide();
}
else if (this.value == 'creditNote') {
$("#InvoiceGrid").hide();
$("#CreditNoteGrid").show();
}
});
$('#showActive').click(function (e) {
if($(this).prop('checked') === true){
var url = '#Url.Action("FilterActiveOnlyAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
else {
var url = '#Url.Action("FilterAllAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
});
});
</script>
}
#Html.Partial("ClientDetailsFormPartial", viewModel.Client)
#if (viewModel.Client.ID > 0)
{
#Html.Partial("ClientDetailsAgreementPartial")
#Html.Partial("InvoiceCreditNoteContainerPartial", viewModel)
}
Partial View - ClientDetailsFormPartial:
#using InvoiceManagement.Models
#model InvoiceClient
#using (#Html.BeginForm("ClientDetails", "Client", FormMethod.Post, new { #id = "frmClientDetails" }))
{
<div class="container-fluid">
<div class="row">
<div class="col-xs-2">
<h2>Client Details</h2>
</div>
<div class="col-xs-2" style="min-height: 70px;">
Search New Client
</div>
<div class="form-group col-xs-2" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="client-ID">Client ID</span>
#Html.TextBox("ID", Model.ID, new { #class = "form-control", #readonly = "readonly" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.ID, String.Empty, new { #class = "help-block" })
</div>
</div>
<div class="form-group col-xs-3" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="accounting-ID">Accounting ID</span>
#if (Model.AID == null && Model.ID == 0)
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control" }) }
else
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control", #readonly = "readonly" }) }
</div>
</div>
<div style="padding-top: 22px;">
<div class="has-error">
#Html.ValidationMessageFor(m => m.AID, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-7">
<div class="input-group">
<span class="input-group-addon" id="client-name">Client Name</span>
#Html.TextBoxFor(m => m.InvoiceClientName, new { #class = "form-control", #name = "InvoiceClientName" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.InvoiceClientName, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-1">Default Tax Code 1</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID1, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode1, new { #class = "form-control", #id = "default-tax-code1-ID", #name = "defaultTaxCodeID1" })
</div>
</div>
<div class="form-group col-xs-3 col-xs-offset-1">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-2">Default Tax Code 2</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID2, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode2, new { #class = "form-control", #id = "default-tax-code2-ID", #name = "defaultTaxCodeID2" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="status">Status</span>
#Html.DropDownListFor(m => m.StatusID, (IEnumerable<SelectListItem>)ViewBag.PopulateStatus, new { #class = "form-control", #id = "status-ID", #name = "statusID" })
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-7">
#if (Model == null || Model.ID == 0)
{
<button type="submit" class="btn btn-default">Add New Client</button>
}
else
{
<button type="submit" class="btn btn-default">Update Existing Client</button>
}
</div>
</div>
</div>
}
Since disabled controls will not post back, its pointless to generate all that extra html, and since readonly controls cannot be edited, again it seems pointless to generate all that extra html and then send it all back unchanged to the server when you submit your form.
A better approach, performance wise would be to have 2 partial views (say) _ClientDetails.cshtml and _ReadOnlyClientDetails.cshtml. The first would contain your form and its editable controls and submit button, and the second would contain only the text values of your properties, for example
#Html.DisplayNameFor(m => m.InvoiceClientName)
#Html.DisplayFor(m => m.InvoiceClientName)
Then in your controller method that generates you main view, set a view model property (or ViewBag property) to indicate which partial to display, for example
ViewBag.IsReadonly = true; // or omit depending on your logic
and in the main view
#if(ViewBag.IsReadonly)
{
#Html.Partial("_ReadOnlyClientDetails", viewModel.Client)
}
else
{
#Html.Partial("_ClientDetails", viewModel.Client)
}
Side note: Everything between you first #{ ... } except ViewBag.Title = "Client Details"; belongs in the controller method, not the view. And to do something like viewModel.Client = Model; makes no sense at all. Your view should be #model InvoiceCreditNoteViewModel and since you're not passing a model to the view, then viewModel.Client = Model; would not make sense anyway since its always null.
Its also not clear why your using Session. The code in your controller should be something like
IList<User> userRoleList = _homeService.GetUserDetails(identity.User.ToString());
int userID = userRoleList.First().ID;
IList<PartialRole> partialRoleList = _homeService.GetPartialDetails(userID)
List<int> values = new List<int>(){ 2, 3 };
if (userRoleList.Any(x => values.Contains(x.RoleID)) && partialRoleList.Any(x => values.Contains(x.RoleID)))
{
ViewBag.IsReadonly = true;
}
I have a dropdown in my view. Based on the selection, i insert a partial view into a div (placeholder) in view. Below is the View.
<div class="container">
<div class="row">
<div class="col-lg-4"><p class="lead">What do you want to do?</p></div>
<div class="col-lg-8">
<select id="myDropDown">
<option id="0" selected>I want to..</option>
<option id="1">Reset my password</option>
</select>
</div>
</div>
<div id="partialPlaceHolder" style="display:none;"> </div>
<script type="text/javascript">
$(document).ready(function () {
$('#myDropDown').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).find('option:selected').attr('id');
/* Request the partial view with .get request. */
$.get('/Requests/FindPartial/' + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
So when I select, "Reset my password" in the dropdown, I am successfully inserting my partial view into the div in my view. Below is my partial view.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-12">
<div class="well well-lg" style="text-align:left">
<div class="form-horizontal" id="resetpasswordform">
<h4>Reset Password</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ServersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ServerName, new SelectList(Model.ServersList))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="submitButton" value="Reset" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(function () {
$("#submitButton").click(function () {
debugger;
$.ajax({
type: "POST",
url: "Requests/Do_ResetPassword",
data: $("#resetpasswordform").serialize(),
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
});
});
</script>
The problem is when the submit button is clicked, and I make the ajax post call, the $("#resetpasswordform").serialize() is always "" (empty string).
I tried making the view just with one element. I verified that the elements have name attribute for serialize to work. I also confirmed that I don't have a type=submit in my button. I changed the resetpasswordform into a form instead of div. I even rendered the partial view directly in Index.cshtml without dynamically populating. Nothing fixed the problem. All the time it returns empty string.
I verified all other similar questions in SO and not getting any hint on what i am doing wrong. Please help.
How about you set the id in the form tag:
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { Id = "resetpasswordform" }))
and remove it from the div.