How to retrieve value from textbox - asp.net

Hi I am trying to retrieve the value from the textbox (Email), however i do not know how to do so as i am new ASP.NET MVC5.
Currently i have this code that gets require the user to enter their email.
<div class="form-group">
#Html.LabelFor(Function(m) m.Email, New With {.class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(Function(m) m.Email, New With {.class = "form-control"})
</div>
</div>
And below is the method that will create a pop up to get user's acknowledgement on the creation of an account.
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</div>
//the code below is #myModel
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to Register an account</p> // want to add the email that was input in the textbox earlier on**
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" value="Register"> Submit </button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
The controller for register is below
Public Function Register() As ActionResult
Return View()
End Function
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Async Function Register(model As RegisterViewModel) As Task(Of ActionResult)
If ModelState.IsValid Then
Dim user = New ApplicationUser() With {
.UserName = model.Email,
.Email = model.Email
}
Dim result = Await UserManager.CreateAsync(user, model.Password)
If result.Succeeded Then
Await SignInManager.SignInAsync(user, isPersistent:=False, rememberBrowser:=False)
Return RedirectToAction("Index", "Home")
End If
AddErrors(result)
End If
Return View(model)
End Function

<div class="form-group">
#Html.LabelFor(Function(m) m.Email, New With {.class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(Function(m) m.Email,, new { id = "EmailID", #clas= "orm-control", placeholder = "EmailID" })
</div>
</div>
And on javascript U can get the value like this
var meetingRoom = $('#meetingRoom').val();

Related

ASP:NET web api problem with dropdown menu

I'm making Hotel management web app, and working on part where i need to add rooms ,problem is with dropdown menu, while adding knew code , I don't know why my dropdown menu stopped working ,it wokrked perfectly before but when added another part of code, dropdown just stoped wokring(when i click on it it wont drop), i removed code that i added before but a dropdown menu still doesent work.I added the part with the dropdown menu below
**index.cshtlm**
#model HotelManagement.ViewModel.RoomViewModel
{
ViewBag.Title = "Index";
}
<pre>
<div id="divAddRoom" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Room</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="form-group ">
</pre>
#Html.LabelFor(model => model.RoomNumber)
#Html.TextBoxFor(model => model.RoomNumber, new { #class = "form-control", id = "txtRoomNumber" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomPrice)
#Html.TextBoxFor(model => model.RoomPrice, new { #class = "form-control", id = "txtRoomPrice" })
</div>
<div class="form-group ">
#Html.LabelFor(model => model.BookingStatusId)
#Html.DropDownListFor(model => model.BookingStatusId, #Model.ListOfBookingStatus, new { #class = "form-control", id = "ddBookingStatus" })
</div>
<div class="form-group ">
#Html.LabelFor(model => model.RoomTypeId)
#Html.DropDownListFor(model => model.RoomTypeId, #Model.ListOfRoomType, new { #class = "form-control", id = "ddRoomType" })
</div>
<div class="form-group ">
#Html.LabelFor(model => model.RoomCapacity)
#Html.TextBoxFor(model => model.RoomCapacity, new { #class = "form-control", id = "txtRoomCapacity" })
</div>
<div class="form-group ">
#Html.LabelFor(model => model.RoomDescription)
#Html.TextBoxFor(model => model.RoomDescription, new { #class = "form-control", id = "txtRoomDescription" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomImage)
<input id="UpLoadImage" type="file" class="form-control" name="roomImage" title="Load Image" onchange="DisplayImage(this)" />
<img id="imgRoom" height="200" width="280" style="border:solid" />
</div>
</div>
</div>
<div class="modal-footer">
<button id="btnSave" type="button" class="btn btn-success">Save</button>
<button type="button" data-dismiss="modal" class="btn btn-danger">Close</button>
</div>
</div>
</div>
Room_controler
enter code here
public ActionResult Index(){
RoomViewModel objRoomViewModel = new RoomViewModel();
objRoomViewModel.ListOfBookingStatus = (from obj in objHotelDbEntities.BookingStatus
select new SelectListItem()
{
Text = obj.BookingStatus,
Value = obj.BookingStatusId.ToString()
}).ToList();
objRoomViewModel.ListOfRoomType = (from obj in objHotelDbEntities.RoomTypes
select new SelectListItem()
{
Text = obj.RoomTypeName,
Value = obj.RoomTypeId.ToString()
}).ToList();
return View(objRoomViewModel);
}
image of the problem

Download text file via ASP.NET MVC dynamically changed

I have to generate file depending on input (checkboxes) and download it:
[HttpGet]
public FileResult GenerateFormatSettingsFile(IEnumerable<string> values)
{
var content = FileSettingsGenerator.Generate(values);
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine(content);
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
And on my view this:
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
$(document).ready(function() {
$("#GenetateFormatSettingsFile").click(function() {
var f = {};
var checkboxes = [];
$('input:checked').each(function() {
checkboxes.push($(this).attr("value"));
});
f.url = '#Url.Action("GenerateFormatSettingsFile", "Home")';
f.type = "GET";
f.dataType = "text";
f.data = { values: checkboxes},
f.traditional = true;
f.success = function(response) {
};
f.error = function(jqxhr, status, exception) {
alert(exception);
};
$.ajax(f);
});
});
</script>
The problem is the download doesn't start. How could I fix it?
If I do it with Html.ActionLink, the download starts, but I can't pass the values of checkboxes which is done by my ajax function above
Thanks!
Edit - that's how my check-boxes looks like:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal" id="formatterSettings" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Settings</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="defaultG">To default view</label>
<input class="form-control" type="checkbox" value="Default" id="defaultG">
</div>
<div class="form-group">
<label for="extendedG">To extended view</label>
<input class="form-control" type="checkbox" value="Extended" id="extendedG">
</div>
/div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-6">
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
#Html.ActionLink("Generate!", "GenerateFormatSettingsFile")
</div>
<div class="col-md-6">
<a class="btn btn-primary" data-dismiss="modal" >Generate From Code</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Put a submit button in your form and POST your form synchronously (without ajax).
when a form is posted, values of all input elements (TextBoxes, CheckBoxes, ...) are sent to the server (with the request) and you don't need to do anything.

When model is not valid, return to partial view inside a view, with error message using asp.net core

I´ve got a modal boostrap. I want to show the error of validation on boostrap modal. But when I leave the model empty and click on submit button Its just viewed as a standalone page.
Partial view:
#model WebApplication1.Models.Book
<form asp-controller="Home" asp-action="AddBook"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#frmaddbook">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Header of Modal</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="BookDescription" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookDescription" class="form-control" />
<span asp-validation-for="BookDescription" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
Index View :
<div class="panel panel-primary">
<div class="panel-body">
<div class="btn-group">
<a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
data-target="#modal-book">
<i class="glyphicon glyphicon-plus"></i>
Add Book
</a>
</div>
</div>
i use this libraries at top of index view:
jquery.unobtrusive-ajax.min.js
jquery.validate.unobtrusive.min.js
and use at the bottom of index view:
<script src="~/js/book-index.js"></script>
book-index.js:
(function ($) {
function Home() {
var $this = this;
function initilizeModel() {
$("#modal-book").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Home();
self.init();
})
}(jQuery))
Controller:
[HttpGet]
public IActionResult AddBook()
{
var b = new Book();
return PartialView("_AddBook", b);
}
[HttpPost]
[ValidateAntiForgeryToken]
//[HandleError]//not in core
public IActionResult AddBook(Book model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return PartialView("_AddBook", model);
}
Model :
public class Book
{
[Key]
public int BookId { get; set; }
[Display(Name = "Book Name :")]
[Required(ErrorMessage = "Enter Book Name Please ")]
public string BookName { get; set; }
[Display(Name = "Book Description")]
[Required(ErrorMessage = "Enter Book Description Please ")]
public string BookDescription { get; set; }
}
My code is shown above. How can i show validation error in modal partial view ?
You can set the Id of form as the data-ajax-update property value of the form , which is ajaxified. This value will be used as the jQuery selector when the result is received from the ajax call.
#model Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#myform">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Add Book</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
Now when you submit the form and model state validation fails, the action method code will return the partial view result with the validation error messages (generated by the validation helpers) and the jquery.unobtrusive-ajax.js library code will replace (because we specified that with data-ajax-mode="replace") the content of the result of the jquery selector #data-ajax-update (the form tag and it's inner contents) with the response coming back from the server.

ASP MVC : submit button is not working , when using AJAX.ActionLink

can you help on this please :
The submit button is not working in simple ASP MVC page after trying to open the bootstrap modal , using AJAX.ActionLink, but when I try top open directly (without AJAX.ActionLink) it is working and then calling the controller's action at server side : here is the code
Main Page : index.cshtml
#model IEnumerable<TestQuestionsAnswers.Models.Question>
#{
ViewBag.Title = "Index";
}
<script>
function ShowPopup() {
$("#divmodal").attr('data-toggle', 'modal');
$('#divmodal').modal('show');
}
</script>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup" }, new { #class = "btn btn-info btn-sm" })
</p>
<!-- Modal -->
<div id="divmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Question</h4>
</div>
<div class="modal-body">
<div class="container" id="divresponse">Data is here....</div>
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Please Note: from the code above I am using this :
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup
to open the modal window .
the Edit.chtml:
#model TestQuestionsAnswers.Models.QuestionEditView
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm("Save", "Question", FormMethod.Post))
{
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save" >
}
and the controller 's action which supposed to reach is :
[HttpPost]
public ActionResult Save(string btnsubmit, TestQuestionsAnswers.Models.QuestionEditView questedit)
{
if (btnsubmit == "Save")
{
List<Answer> UpdatedAnswers=questedit.Answers;
dbaccess.SaveEditQuestionsBy(questedit);
}
return RedirectToAction("Index");
}
I appreciate your help
I dont know you have installed unobtrusive-ajax package or not
but if not first go to manage nudget package -> search ajax and install Microsoft.jquery.unobtrusive-ajax.js package
then give this reference in your cshtml
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
then put debugger in controller and check whether method is firing or not.

ASP.Net Razor MVC Bootstrap Login Modal Validation

Using Bootstrap in my Razor page, I am opening a modal window:
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target=".navbar-offcanvas" data-canvas="body">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand pull-right" href="#">
<img src="assets/img/logo-header.png" alt="Alternate Text for Image">
</a>
</div>
<div class="navbar-offcanvas offcanvas navmenu-fixed-left">
<a class="navmenu-brand" href="#">eServices</a>
<ul class="nav nav-justified">
<li>New Here?</li>
<li>Services</li>
<li>Sign In</li>
</ul>
</div>
</div>
</div>
<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>
<h3 class="modal-title" id="myModalLabel">Login to MyApplication</h3>
</p>
</div>
#using (Html.BeginForm("index", "home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<div class="form-group #Html.ValidationErrorFor(m => m.Username, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormTextBoxFor(p => p.Username, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Username))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Username, null, new { #class = "help-block" })
</div>
</div>
<div class="form-group #Html.ValidationErrorFor(m => m.Password, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormPasswordFor(p => p.Password, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Password))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "help-block" })
</div>
</div>
#Html.ValidationSummary(true, string.Empty, new { #class = "test" }, "span")
<div class=" pull-right">
<p>
<button type="submit" class="btn btn-default">#Forms.ButtonSignin</button>
</p>
<br />
<p>
#Html.ActionLink("Forgot your username?", "ForgotUsername")
</p>
<p>
#Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>
</div>
}
</div>
</div>
</div>
The issue I have is that, for example, I entered an incorrect username/password combination, the form validates, but the modal window closes. Is there a way to re-open the modal window after the form has posted if the validation triggered an error?
You could add a property named IsModalShown i.e.
public class AModel
{
public bool IsModalShown { get; set; }
}
Render this as a hidden for in your view i.e.
#Html.HiddenFor(m => m.IsModalShown)
When the modal is opened set the hidden value to true, this will enable the modal state to be posted back to the controller action i.e.
$('#modalLogin').on('show.bs.modal', function (e) {
$('#IsModalShown').val(true);
})
Please note the above will depend on the version of bootstrap you are using but there are other docs on the official site
Then add the following to your view that automatically pops it up
$(function(){
#if(Model.IsModalShown)
{
$('#signin_modal').modal('show');
}
});
I had a similar problem, but didn't have a model in view. Posting my solution, in case it would help someone. I wanted to show an error message stored in TempData (in case of wrong login/password combination, on which Batuta was asking).
Controller:
public ActionResult SignIn(string login, string password)
{
if (Membership.ValidateUser(login, password))
{
// something
}
else
{
TempData["message-error"] = "Wrong combination";
}
return RedirectToAction("Index", "Home");
}
Showing the message in modal window:
#if (TempData["message-error"] != null)
{
#TempData["message-error"]
}
Opening modal in index:
#if (TempData["message-error"] != null)
{
<script type="text/javascript">
$('#myModal').modal('show');
</script>
}
Maybe not that clean, but works for me.

Resources