change the button text without page refreshing in mVC4 - c#

I am doing my application in MVC. In my view i have one textbox named as EmailId, and one Submit button. If i enter the Email id and submit the button,the Label of the button want to change as Verify and the text box should be cleared without refreshing the page.
My view page is
<div class="sign" id="email">
#using (Html.BeginForm("Randa", "BU", FormMethod.Post))
{
<div class="sign1">
<div class="sign2" style="height:267px;width:562px;margin-left:214px" id="cdiv">
#Html.TextBox("EmailId","", new {#placeholder ="Enter the Email id",id="txtemail "})<br /><br />
<input type="submit" name="submit" value="Sign Up" id="btn" onclick="addbutton()" class="addbutton"/>
</div>
</div>
}
</div>
<div class="drnd" id="rnd" style="display:none">
#using (Html.BeginForm("Ra_verify", "BU", FormMethod.Post))
{
<div class="sign1">
<div class="sign2" style="height:267px;width:562px;margin-left:214px" id="cdiv">
#Html.TextBox("Getran", "", new { #placeholder = "Enter the Randam", id = "txtrnd" })<br /><br />
<input type="submit" name="submit" value="Verify" id="btnrnd" class="addbutton" />
</div>
</div>
}
</div>
}
<script type="text/javascript">
var btxt = "Verified";
document.getElementById("#btn").innerHTML = btxt;
</script>
<script type="text/javascript">
function addbutton()
{
($("#email").hide())
$("#rnd").show();
}
</script>
My controller code is
public ActionResult Randa()
{
return View();
}
[HttpPost]
// send the randam No to the Entered mail id . Store the mail id and randam no into tbl_bussiness table;
public ActionResult Randa(string EmailId, string submit)
{
string userId = System.Configuration.ConfigurationManager.AppSettings["UserTypeId"];
int typeid = Convert.ToInt32(userId);
if (ModelState.IsValid)
{
if (submit != null && EmailId != null)
{
EmailManager.SendConfirmationEmail(EmailId);
tbl_BusinessUser b = new tbl_BusinessUser();
b.EmailId = EmailId;
b.RandomNumber = (int)Session["rnd"];
b.UserTypeId = typeid;
b.CreateDTTM = System.DateTime.Now;
db.tbl_BusinessUser.Add(b);
db.SaveChanges();
ViewBag.message = "Please check ur Mail for randam no.Enter random in textbox ";
}
else
{
ModelState.AddModelError("", "Error");
}
}
return View();
}
public ActionResult Ra_verify()
{
return View();
}
[HttpPost]
// check the random no with table random no ,if match redirect to registration create page
public ActionResult Ra_verify(int EmailId, string submit)
{
if (submit != null)
{
// int c = Convert.ToInt32(EmailId);
tbl_BusinessUser b = new tbl_BusinessUser();
var tbra = db.tbl_BusinessUser.Where(x => x.RandomNumber == EmailId).FirstOrDefault();
//var tbram = Convert.ToInt32(tbra);
return RedirectToAction("Create", "BU");
}
return View();
}
Can anyone please help me?
Thanks in Advance.

We have to use Ajax whenever we want to update the value in the webpage without refreshing.
We have to do following things to make your page work.
Remove BeginForm block from your view because when we use BeginForm, it will send request to controller and refreshes the page.
Use Ajax to pass information to controller and update the page without refreshing it.
As you have two POST actions in controller, so keep both divs "rnd" and "email"
Here is sample script block with Ajax option to update the page as you requested,
$('#btn').click(function () {
var urlinfo = '/Home/Randa';
var textboxValue = $('#txtemail').val();
$.ajax({
type: "POST",
data: { value: textboxValue },
url: urlinfo,
success: function (result) {
$('#email').hide();
$('#rnd').show();
},
error: function () {
alert("failed");
}
});
});

First of all you need to use Ajax.BeginForm
Using Ajax.BeginForm with ASP.NET MVC 3 Razor
And on success function you can write the below code for clear text EmailId, and one Submit button.
$("#EmailId").val("");
$("#btn").val("Verify");
and you don't need two forms, if you are going to do the above.

Related

My cascaded dropdowns losing selected values after submit in ASP.NET Core MVC?

How can I keep selected values for both dropdown after submit action?
In my scenarios, my cascaded dropdown is populating from partial view. I'm new to ASP.NET Core MVC. Let me know if you want more clarifications.
My view:
<form asp-controller="Recommendation" asp-action="SubmitData" method="post">
<select id="States" class="form-control selectpicker" asp-for="StateID" asp-
items="#(new SelectList(ViewBag.StateList,"StateID","State"))"
placeholder="Select Categories"
onchange="console.log($(this).children(':selected').length)">
</select>
#Html.DropDownListFor(m => m.CityID, new SelectList(""), new {#class="select2
form-control", #style = "width: 100%" })
<button id="btnSubmit" class="btn btn-secondary btn-sm">Submit</button>
</form>
onChange function on first dropdown to call 2nd one:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var StateID = $(this).val();
/*debugger;*/
$("#CityID").empty();
$.ajax({
type: "Get",
url: "/Recommendation/GetCityList?iStateID=" + StateID,
contentType: "html",
success: function (response) {
$("#CityID").append(response);
},
error: function (jqXHR, textStatus, errorThrown) {
}
})
})
});
</script>
Partial View for Child dropdown
<option value="">Select City</option>
#if (ViewBag.CityOptions != null)
{
foreach(var item in ViewBag.CityOptions)
{
<option value="#item.Value">#item.Text</option>
}
}
Controller:
[HttpGet]
public ActionResult IndexGet()
{ // From where I get values.
Entity entity = new Entity();
StateList = gateway.SelectList();
StateList.Insert(0, new Model { StateID = 0, State = "Select State" });
ViewBag.StateList = StateList;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitData(RecommendModel recommendModel)
{ // Submit form method and I used RedirectToAction for calling view again.
{
}
return RedirectToAction("IndexGet", "Recommendation");
}
[HttpGet]
public ActionResult GetCityList(long iStateID)
{ // For partial call
Entity entity = new Entity();
MCAlist = entity.GetCityList(iStateID);
ViewBag.CityOptions = new SelectList(MCAlist,"MCAID","MCA");
return PartialView("_CityOptionPartial");
}
Looks like maybe you are using the bootstrap-select plugin. You can try adding $(this).selectpicker('refresh'); at the top of your change event.

ajax.beginform - OnFailure dont return partial view

Hello
I am using ajax.beginform and i want to return partial view with the
errors inside. whan I change the status code to something bad to fire
the OnFailure method it is not returning the partial view. the view that called:
<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" value="Submit">שלח</button>
}
<input type="button" name="next" class="next action-button" value="Next" />
my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
socio.StudentId = sStudentId; // bind student id to socio model
bool sociook = SocioDetValid(socio);
// add validation
if (ModelState.IsValid && sociook)
{
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
}
js:
<script>
$(document).ready(function ()
{
});
function firstsuccess(data) {
console.log(data);
$('#partialsocio').html(data);
console.log('this is ajaxSuccess');
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(data);
$('#partialsocio').html(data);
}
</script>
please help me out with this
If your request fails then you will get the callback from server including problem definition inside sociodetailsfail witin java-script, where you can put logic to display error messages that you receive from server bdata object to user

Info Modal after Confirmation Modal in Razor Pages

I want to show an info modal that says "Record successfully deleted." after clicking the button inside a Confirmation Modal.
Here is my code to show the confirmation modal
Controller
public IActionResult Delete()
{
return PartialView("_ModalDelete");
}
_ModalDelete.cshtml
#using Data.ViewModels.Modal
#using (Html.BeginForm())
{
#await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = "Delete" })
<div class="modal-body form-horizontal">
Are you sure you want to delete this record?
</div>
#await Html.PartialAsync("_ModalFooter", new ModalFooter { SubmitButtonText = "Delete" })
}
Example Screenshot:
This seems to be okay on this part. No issues encounter. But after clicking the Delete button, it will show my modal like a whole view. See below:
Here is my code:
Controller - for post of data after clicking delete button
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
try
{
var validationResult = await new RegionHandler(_regionService).CanDelete(id);
if (validationResult == null)
{
await _regionService.DeleteById(id);
return PartialView("_ModalInfo", new Tuple<string, string>(Constants.Message.Info, Constants.Message.RecordSuccessDelete));
}
ModelState.AddModelError(validationResult);
}
catch (Exception ex)
{
var exceptionMessage = await Helpers.GetErrors(ex, _emailService);
ModelState.AddModelError(new ValidationResult(exceptionMessage));
}
ModelState.AddModelError(string.Empty, "Invalid delete attempt.");
return PartialView("_ModalInfo", new Tuple<string, string>(Constants.Message.Error, ModelState.ToString()));
}
_ModalInfo.cshtml
#using Data.ViewModels.Modal
#model Tuple<string,string>
#await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = Model.Item1})
<div class="modal-body form-horizontal">
#Model.Item2
</div>
#await Html.PartialAsync("_ModalFooter", new ModalFooter { CancelButtonText = "OK", OnlyCancelButton = true})
With the submission of your form you are making a roundtrip to the server, which will issue a completely new html page (even if your html code is only partial).
To remove the question-modal and replace it with a message-modal in the original page (region-list), you will have to use javascript (for the post AND the replacement).
If you want to stick with the roundtrip, make the Delete method return a full html page, which integrates the message-dialog (like the region-list intergrates the question-dialog).
Finally found an answer with this. So basically I just revised everything so that the model validation from controller will still be there.
Heres my code:
For the table markup
<tr>
<td>
#Html.DisplayFor(modelItem => item.RegionName)
</td>
<td>
#Html.DisplayFor(modelItem => item.RegionCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.RegionKey)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td class="text-center">
<a asp-action="Edit" asp-route-id="#item.RegionId"><i class="fa fa-edit text-info"></i></a>
<i class="fa fa-trash text-danger"></i>
</td>
</tr>
where it call a javascript function below:
#section Scripts{
<script type="text/javascript">
function showDeleteConfirmation(message, event, id) {
event.preventDefault();
showConfirmationModal(message).then(function () {
$("#id").val(id);
$("#formDelete").submit();
});
}
</script>
}
where showConfirmationModal() is a promise function that uses bootbox.js (library that wraps bootstrap modal for easier usage).
site.js
function showConfirmationModal(message, title = "Confirm", size = "medium", confirmText = "Yes", canceltext = "No") {
const deffered = $.Deferred();
bootbox.confirm({
title: title,
message: message,
size: size,
buttons: {
confirm: {
label: confirmText,
className: "btn-success"
},
cancel: {
label: canceltext,
className: "btn-danger"
}
},
callback: function (result) {
if (result) {
deffered.resolve(result);
} else {
deffered.reject(result);
}
}
});
return deffered.promise();
}
On callback, it will submit the hidden form below. Ofcourse don't forget to set the id to be deleted.
Hidden form for Delete action
<form method="post" asp-action="Delete" id="formDelete" class="hidden">
<input type="hidden" id="id" name="id" />
<input type="hidden" asp-for="Item1.RegionName" name="RegionName" />
<input type="hidden" asp-for="Item1.Page" name="Page" />
<input type="hidden" asp-for="Item1.SortBy" name="SortBy" />
<input type="hidden" asp-for="Item1.SortOrder" name="SortOrder" />
</form>
To show the Info Message(for success delete), I created a PartialView to make the modal show if theres a data set in a Temporary Data or TempData. This was added under the _Layout.cshtml page:
_ModalScriptsInit.cshtml
#using Data.Utilities
#{
var text = TempData[Constants.Common.ModalMessage];
if (text != null && !text.Equals(string.Empty))
{
<script type="text/javascript">
showDefaultModal("#text");
</script>
}
}
So in my controller once successfully delete I will just set the TempData with its key as shown below:
Controller
[HttpPost]
public async Task<IActionResult> Delete(int id, RegionSearchViewModel searchViewModel)
{
try
{
var validationResult = await new RegionHandler(_regionService).CanDelete(id);
if (validationResult == null)
{
await _regionService.DeleteById(id);
TempData[Constants.Common.ModalMessage] = Constants.Message.RecordSuccessDelete;
return RedirectToAction(nameof(List), searchViewModel);
}
ModelState.AddModelError(validationResult);
}
catch (Exception ex)
{
var exceptionMessage = await Helpers.GetErrors(ex, _emailService);
ModelState.AddModelError(new ValidationResult(exceptionMessage));
}
ModelState.AddModelError(string.Empty, "Invalid delete attempt.");
return RedirectToAction(nameof(List), searchViewModel);
}
I am not sure yet if this is the best way so far. Please give suggestion on how to improve this code. Thanks!

Maximum callstack size exceeded when trying to ajax post a list of selected checkboxes

I have a page which is being populated with a list of checkboxes for each record in the database. The user can select as many checkboxes as they want and the system should save their responses. I'm having a hard time getting my array of selected checkboxes to pass through to my Controller.
When i run my code and click the submit button i get a Maximum call stack size exceeded and i'm not sure how to solve that.
Image of the browser console error message: http://imgur.com/a/BnKLL
.cshtml:
#{
ViewBag.Title = "Subject";
}
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<h2>Explore Subjects</h2>
<div>
<button id="SubmitButton">Save Changes</button>
<div style="border-bottom:solid">
<h4>Your Followed Subjects</h4>
<div id="FollowedSubjects">
#foreach (var subject in Model.FollowedSubjects)
{
<input type="checkbox" name="SubjectCheckBox" checked="checked" value=#subject.SubjectId>#subject.SubjectDetail.Subject<br>
}
</div>
</div>
<div id="AllSubjects">
<br />
<h4>More Subjects to Follow</h4>
<p>Ordered by number of bills with subject</p>
#foreach(var subject in Model.AllSubjects)
{
<div class="subjectDisp">
<input type="checkbox" name="SubjectCheckBox" value=#subject.Subject.SubjectId>#subject.Subject.Subject (#subject.Count) <br>
</div>
}
</div>
</div>
<script>
$(document).ready(function () {
$('#SubmitButton').click(function () {
var checkboxes = document.getElementsByName("SubjectCheckBox");
var checked = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checked.push(checkboxes[i]);
}
}
$.ajax({
url: '#Url.Action("FollowSubjects", "Home")',
type: 'POST',
data: { Parameters: checked },
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
alert("there")
});
});
</script>
My controller funtion that im trying to call.
[HttpPost]
public ActionResult FollowSubjects(int[] Parameters)
{
int i = 0;
return View();
}
Eventually i will have this hit the database but for now i just put a breakpoint at int i = 0; to see what gets passed to the function.
You can send it as an array of string and convert them to int at server side or Stringify it and send
var checked=""
$(checkboxes).each(function () {
checked += this + ',';
i++;
ajax --> data: { Parameters: checked },
[HttpPost]
public ActionResult FollowSubjects(string Parameters)
{
// Do your task
return View();
}

How to capture ajax drop down list value in MVC 3 view?

I have the following view that has tow dropdowns and one button:
#model RoomReservation.Webb.Models.HomeViewModel
#{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<fieldset>
<legend>Select a city and a hotel</legend>
<br />
<br />
<br />
#Html.DropDownListFor(x=>x.City_DDL_ID, new SelectList(Model.AllCities, "Value", "Text"),"...pick a city..." )
<br />
<br />
#Html.DropDownListFor(x => x.Hotel_DDL_ID, Enumerable.Empty<SelectListItem>(), "...pick a hotel...", new { disabled = "disabled"})
<br />
<br />
<input id="SearchButton" type="submit" onclick="window.location.href='/Home/SearchForRooms'" disabled="disabled"/>
</fieldset>
<script type="text/javascript" language="javascript">
$('#City_DDL_ID').change(function () {
var selectedCity = $(this).val();
if (selectedCity != null && selectedCity != '-1') {
$.getJSON('#Url.Action("GetHotels")', { id: selectedCity }, function (hotels) {
var hotelsSelect = $('#Hotel_DDL_ID');
hotelsSelect.empty();
$.each(hotels, function (index, hotel) {
hotelsSelect.append($('<option/>',
{
value: hotel.Value,
text: hotel.Text
}));
});
$('#Hotel_DDL_ID').attr('disabled', false);
$('#SearchButton').attr('disabled', false);
});
}
});
</script>
<script type="text/javascript" language="javascript">
function onsubmitclcik() {
var SecondDrpId = $('#Hotel_DDL_ID').val();
window.location.href = '/Home/SearchForRooms?parameter=' + SecondDrpId;
}
I would like to get a value from second dropdown so that I can give it as paramater to my method f**ired from the button atribute "onclick". It is now working (above script).
But my action still gets null parameter. Here is the code:
public ActionResult SearchForRooms(int SecondDrpId)
{
if (SecondDrpId > -1)
return View(); //Here goes some model, not important
else
return RedirectToRoute("Home/Index");
}
Here is the Chrome parameter:
Request URL:http://localhost:22191/Home/SearchForRooms?parameter=3
Request Method:GET
thank you**
You can use following code to solve your problem.
<input id="SearchButton" type="submit" onclick="onsubmitclcik();" disabled="disabled"/>
Write a javascript function to call your next url,
function onsubmitclcik() {
var SecondDrpId = $('#Hotel_DDL_ID').val();
window.location.href = '/Home/SearchForRooms?parameter=' + SecondDrpId;
}
Why are you calling your action by setting window.location.href to your actions url?
That way, not a single parameter will be sent to your action.
Either add the parameter to the url and name it like your action paramter is named. In your example the parameter has to be called SecondDrpId:
onclick="window.location.href='/Home/SearchForRooms?SecondDrpId=' + $('#Hotel_DDL_ID').val()"
Or embed your dropdowns inside a form and post it to your action method.

Categories