I'm new to ASP.Net Core 2.1 MVC and C#,
I couldn't figure out what's wrong with the code.
I'm using Sweet Alerts as dialog confirmation before any post actions,
it works but it redirects instantly to the index page, the line below didn't even executed properly.
swal("Saved!", "Your record has been saved.", "success");
I want it to redirect to the index page only after the user clicks 'OK' and the alert closed properly (like fade out)
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
swal({
title: "Save Changes?",
text: "",
type: "info",
showCancelButton: true,
cancelButtonClass: 'btn-secondary waves-effect',
confirmButtonClass: 'btn-success waves-effect waves-light',
confirmButtonText: "Yes",
closeOnConfirm: false
}, function () {
$("#studentForm").submit();
swal("Saved!", "Your record has been saved.", "success");
});
});
});
I tried switching the lines
$("#studentForm").submit();
swal("Saved!", "Your record has been saved.", "success");
to
swal("Saved!", "Your record has been saved.", "success");
$("#studentForm").submit();
but it didn't work.
This is my Edit view:
#model CIMS.Models.Plans
#{
ViewData["Title"] = "Edit";
}
<div class="row">
<div class="col-xs-12">
<div class="page-title-box">
<h4 class="page-title">Edit Plan</h4>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="card-box table-responsive">
<form asp-action="Edit" id="studentForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="PlanID" />
<div class="form-group">
<label asp-for="PlanName" class="control-label">Plan Name</label>
<input asp-for="PlanName" class="form-control" />
<span asp-validation-for="PlanName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BillCutOffLimit" class="control-label">Bill Cut-off Limit</label>
<input asp-for="BillCutOffLimit" class="form-control" />
<span asp-validation-for="BillCutOffLimit" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<button type="submit" value="Save" class="btn btn-success waves-effect waves-light w-sm" id="btnSave">
<span class="btn-label"><i class="fa fa-check"></i></span>
Save
</button>
<a asp-action="Index" class="btn btn-primary waves-effect waves-light w-sm">
<span class="btn-label"><i class="fa fa-arrow-left"></i></span>
Back
</a>
</div>
</form>
</div>
</div>
</div>
and this is the http post edit action under the controller:
// POST: Plans/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("PlanID,PlanName,Description,BillCutOffLimit,ModifiedBy,DateModified,ModifiedByComputerUsed")] Plans plans)
{
if (id != plans.PlanID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Attach(plans);
plans.ModifiedBy = User.Identity.Name;
plans.DateModified = DateTime.Now;
plans.ModifiedByComputerUsed = Environment.MachineName;
_context.Entry(plans).Property(x => x.PlanName).IsModified = true;
_context.Entry(plans).Property(x => x.Description).IsModified = true;
_context.Entry(plans).Property(x => x.BillCutOffLimit).IsModified = true;
_context.Entry(plans).Property(x => x.DateModified).IsModified = true;
_context.Entry(plans).Property(x => x.ModifiedBy).IsModified = true;
_context.Entry(plans).Property(x => x.DateModified).IsModified = true;
//_context.Update(plans);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PlansExists(plans.PlanID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(plans);
}
any idea?
Not sure which version of sweetalert.js you are using but the below code works with 2.1.0 of https://sweetalert.js.org/
You need to use the Promise based design for sweetalert . When you click on the first confirm before saving the changes it returns a Promise of boolean value which signifies whether the user has confirmed the action or not. You need to resolve the promise to check this boolean value.Based on this value you need to create another instance of swal and similarly resolve it to make the Ajax call like below -
sample code for Ajax call
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
swal({
title: "Save Changes?",
text: "",
type: "info",
showCancelButton: true,
cancelButtonClass: 'btn-secondary waves-effect',
confirmButtonClass: 'btn-success waves-effect waves-light',
confirmButtonText: "Yes",
closeOnConfirm: false
})
.then(val => {
if (!val) throw null;
swal("Saved!", "Your record has been saved.", "success")
.then((confirm) => {
$("#studentForm").submit();
})
});
});
$("#studentForm").on('submit',function(){
alert('form POST');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<link href="http://tristanedwards.me/u/SweetAlert/lib/sweet-alert.css" rel="stylesheet"/>
<form id="studentForm" method="POST">
name : <input type="text" id="fullname" /> <br>
<button id="btnSave">
Save
</button>
</form>
Working fiddle : http://jsfiddle.net/3e7fgtop/
Related
I have a partial view that will not show the result that it gets from the controller. This is in ASP.NET Core MVC 2.1.
The base for the code is from here.
Here is the partial view:
#model City
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Grad</h4>
</div>
<div class="modal-body">
<form asp-controller="City" id="TestForm">
<div class="form-group">
<label class="control-label">Name</label>
<input asp-for="Name" class="form-control" id="CityName" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Postal Code</label>
<input asp-for="PostalCode" class="form-control" id="PostalCode" onkeypress="return isNumberKey(event)" />
<span asp-validation-for="PostalCode" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Country TEST</label>
<input type="text" id="txtCounty" name="CountyName"/>
<input type="hidden" id="hfCountry" name="CountyID" />
<span asp-validation-for="CountryID" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default" id="SaveCity" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="CloseCity" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The part in question is:
<div class="form-group">
<label class="control-label">Country TEST</label>
<input type="text" id="txtCounty" name="CountyName"/>
<input type="hidden" id="hfCountry" name="CountyID" />
<span asp-validation-for="CountryID" class="text-danger"></span>
</div>
It does not want to show the result it gets.
The jQuery method I use is, it is inside the Index.cshtml scripts:
$(document).on("focus", "#txtCountry", function (e) {
$("#txtCountry").autocomplete({
source: function (request, response) {
$.ajax({
url: '/City/AutoComplete/',
type: "POST",
data: { "prefix": request.term },
success: function (data) {
response($.map(data, function (item) {
return item;
}))
}
});
},
select: function (e, i) {
$("#hfCountry").val(i.item.val);
},
minLength: 1
});
});
When I put this code:
<input type="text" id="txtCounty" name="CountyName"/>
<input type="hidden" id="hfCountry" name="CountyID" />
outside the partial view it shows the searched for thing.
Here is controller for it:
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var countries = (from country in this._dbContext.Countries
where country.Name.ToLower().Contains(prefix.ToLower())
select new
{
label = country.Name,
val = country.ID
}).ToList();
return Json(countries);
}
Can anybody help I just can not find the answer.
I found the answer.
The text was showing behind the modal, that is way I could not see it.
<style>
.ui-autocomplete {
z-index: 5000;
}
</style>
Put that inside the _Layout.cshtml file, inside the enviroment.
<environment include="Development">
... some stuff...
<style>
.ui-autocomplete {
z-index: 5000;
}
</style>
... some ,oe stuff...
</environment>
Code searchView and PartialResultView
SearchView
#model Shared.Model.Search.GLSearch
#{
ViewData["Title"] = "Search GL";
}
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box">
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item">UBold</li>
<li class="breadcrumb-item">Forms</li>
<li class="breadcrumb-item active">Elements</li>
</ol>
</div>
<h4 class="page-title">Search Customer</h4>
</div>
</div>
</div>
<!-- end page title -->
<form asp-action="" asp-controller="" method="post">
<div class="row">
<div class="col-lg-12">
<div class="card-box">
<div class="form-row">
<div class="form-group col-md-2">
<label asp-for="Name" class="col-form-label"></label>
<input asp-for="Name" type="text" class="form-control" />
</div>
<div class="form-group col-md-2">
<label asp-for="Code" class="col-form-label"></label>
<input asp-for="Code" type="text" class="form-control" />
</div>
<div class="form-group col-md-3">
<label asp-for="GLSectionId" class="col-form-label">Section </label>
<select asp-for="GLSectionId" asp-items="#(new SelectList(Model.glSections,"Id","Name"))" class="form-control">
<option value="">Choose</option>
</select>
</div>
<div class="form-group col-md-3">
<label asp-for="GLGroupId" class="col-form-label">Group</label>
<select asp-for="GLGroupId" asp-items="#(new SelectList(Model.glGroups,"Id","Name"))" class="form-control">
<option value="">Choose</option>
</select>
</div>
<button type="button" id="search" class="btn btn-primary waves-effect waves-light">Search</button>
</div>
</div> <!-- end card-box -->
</div> <!-- end col -->
</div> <!-- end row -->
</form>
<div id="view-all"></div>
Search_PartiaView
#model PagedResult<Shared.Model.Masters.GLMaster.GLViewModel>
#{
}
#if (Model == null || Model.RowCount == 0)
{
<p>No results found</p>
}
else
{
<div class="col-lg-12">
<div class="card-box">
<h4 class="header-title">Customers</h4>
<p class="sub-header">
</p>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
<th data-priority="1">#</th>
<th data-priority="3">Name</th>
<th data-priority="6">Code</th>
<th data-priority="6">Section</th>
<th data-priority="6">Group</th>
<th data-priority="6">
<a onclick="showInPopup('#Url.Action("AddOrEditGL","GLMaster",new {area = "Masters"},Context.Request.Scheme)','New GL')" class="btn btn-success text-white"><i class="fas fa-random"></i> New GL</a>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Results)
{
<tr>
<th scope="row">#item.Id</th>
<td>#item.Name</td>
<td>#item.Code</td>
<td>#item.GLSection</td>
<td>#item.GLGroup</td>
<td>
<div>
<a onclick="showInPopup('#Url.Action("AddOrEditGL","GLMaster",new { area= "Masters",id = item.Id},Context.Request.Scheme)','Update GL')" class="btn btn-info text-white"><i class="fas fa-pencil-alt"></i> Edit</a>
<form asp-area="Masters" asp-action="DeleteGL" asp-route-id="#item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
<input type="submit" value="Delete" class="btn btn-danger" />
</form>
</div>
</td>
</tr>
}
</tbody>
</table>
</div> <!-- end table-responsive-->
</div> <!-- end card-box -->
</div> <!-- end col -->
<!-- Responsive Table js -->
}
Partial View (AddEditGL)
#model Shared.Model.Masters.GLMaster.GLModel
#{
Layout = null;
ViewData["Title"] = "Add Customer";
}
<div class="row">
<div class="col-lg-12">
<div class="card-box">
<form asp-action="AddOrEditGL" asp-controller="GLMaster" asp-area="Masters" asp-route-id="#Model.Id" onsubmit="return jQueryAjaxPost(this);">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="#Model.Id" />
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" type="text" class="form-control">
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label asp-for="NameLang" class="control-label"></label>
<input asp-for="NameLang" type="text" class="form-control">
<span asp-validation-for="NameLang" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 offset-md-3">
<input type="submit" value="Submit" class="btn btn-primary btn-block" />
</div>
</div>
</form>
</div> <!-- end card-box -->
</div> <!-- end col -->
</div> <!-- end row -->
I have View with Partial view (is for results in table) . When i click Edit button in Search_PartiaView
i need to open popup (Partial View (AddEditGL))
and data should be loaded ajax and submit the button after update.. I need to use jquery unobtrusive validation in popup and also without refresh the page ..Please let me know hw to do..Thanks
EDIT
I Have implemented similar to this Ajax crud popup
I Have Main view and Partial view. Also AddOrEdit View for Add/edit Master.
My Current solution works.. But inmy main view i have filter based on 2 filds.
After add/edit grid load all the result but if filter applied i also need to filter the grid ..
My Javascript code Here:
jQueryAjaxPost = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
if (res.isValid) {
$('#view-all').html(res.html) --- here actually data coming all without filter
$('#form-modal .modal-body.p-4').html('');
$('#form-modal .modal-title').html('');
$('#form-modal').modal('hide');
showAll(4, 1); --- it is the javascript fuction call to call the
api again
}
else
$('#form-modal .modal-body.p-4').html(res.html);
},
error: function (err) {
console.log(err)
}
})
//to prevent default form submit event
return false;
} catch (ex) {
console.log(ex)
}
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEditGL(int id,GLModel glModel)
{
if (ModelState.IsValid)
{
var mappedGL = _mapper.Map<GLDTO>(glModel);
//Insert
if (id == 0)
{
await _glService.CreateGL(mappedGL);
}
//Update
else
{
await _glService.UpdateGL(mappedGL);
//Call Update
}
// How do i filter the based on Main view form controls
return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_GLViewAll", null) });
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEditGL", glModel) });
}
my Current solution call the api again ( 2 server calls) one for update and another for call update table .. i need to do the same in single call ..Please help to do?
Note: I dont need complete solution , I only need to how to get the AddOrEditGL Controller post method Main view form control text fieds text to filter in DB
If you want to update/add and show the searched data in one request,The quick way is to copy the SearchGLPartial code to the AddOrEditGL function and pass the pageSize,pageIndex,name,code,GLSectionId and GlGroupId by ajax:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEditGL(int id,GLModel glModel,string name,string code,string GLSectionId,string GlGroupId...)
{
if (ModelState.IsValid)
{
var mappedGL = _mapper.Map<GLDTO>(glModel);
//Insert or
//Update
//copy the SearchGLPartial code here and return view with data
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEditGL", glModel) });
}
If you just do not want to remove showViewAll() jquery,I think you could set session for the filter condition when you first search the data in SearchGLPartial action.Then in your AddOrEdit action,get the session and set the correct url.Finally,you could get the url in ajax success response:
public IActionResult SearchGLPartial(string name,string code,string GLSectionId,string GLGroupId)
{
HttpContext.Session.SetString("name", name);
HttpContext.Session.SetString("code", code);
HttpContext.Session.SetString("GLSectionId", GLSectionId);
HttpContext.Session.SetString("GLGroupId", GLGroupId);
var data = Gllist.Where(a => a.Name.Contains(name) & a.Code.Contains(code)).FirstOrDefault();//filter by yourself
return PartialView("_Search", data);
}
AddOrEdit:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEditGL(int id,GLModel glModel)
{
if (ModelState.IsValid)
{
//Insert
//Update
var name = HttpContext.Session.GetString("name");
//other session data...
return Json(new { isValid = true, url="Home/Index?name="+name+"&code="+xxx+"&...."});
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEditGL", glModel) });
}
Then your ajax:
success: function (res) {
if (res.isValid) {
window.location.href = response.url;
}
else
$('#form-modal .modal-body.p-4').html(res.html);
},
I recommend using the jQuery Unobtrusive AJAX library. Its very easy to use:
It can fetch partial views and place them in a container of your choice using the
data-ajax-update="#panel"
Click here
<div id="panel"></div>
This is an example of a controller action that would return the modal:
public IActionResult GetEditModal() => Partial("ViewName");
Then when the modal is placed in your container, using the data-ajax-success attribute a callback method is called, parse the form using the jQuery Unobtrusive Validation like this:
function SuccessCallback() {
//You can also use the keyword "this" instead of getting the form with jquery
$.validator.unobtrusive.parse($(this));
//or
$.validator.unobtrusive.parse($form);
}
Very useful resources : Link - jQuery Unobtrusive AJAX - GitHub
Update
What i did in previous projects is to include an empty edit modal (a modal with an empty body) then using the library and the data-ajax-update i would replace the body of that modal every time the user pressed the edit button on a table item like this:
<div class="modal fade" id="eModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content id="modalContentE">
<div class="modal-header">
<h4 class="modal-title"><i class="nav-icon fas fa-edit"></i> Edit Data</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true"><i class="fas fa-times-circle text-white"></i></span>
</button>
</div>
//New data goes here
</div>
</div>
</div>
And your add Modal would be a regular full modal and each time the user use it to submit data, clear the form.
I'm trying to refresh my Partial View after submitting a form which will be processed in my controller. The problem is that whenever I try to refresh it form my controller, I get redirected to a blank page with content from the Partial View.
Partial View
#model Smarty.Viewmodels.BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
#if (!string.IsNullOrWhiteSpace(ViewBag.message))
{
if (!ViewBag.IsError)
{
<span class="border border-success text-success">#ViewBag.message</span>
}
else
{
<span class="border border-danger text-danger">#ViewBag.message</span>
}
}
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="submit" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
Controller
public async Task<IActionResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
return PartialView("BugModal", viewModel);
}
Thanks in advance!
I get redirected to a blank page with content from the Partial View.
That is expected because you use return PartialView() which will return the simple partial html to render it into the view.
I want to refresh the Partial View with content like Error Messages, Success messages etc
You could not get #ViewBag.message from the SendBugReport action, it is passed from the action of main page.
As the comment has said that, first of all, you could use ajax to submit the form to SendBugReport action.Then the action return message and isError json data to ajax success function. Finally, you render message on the view based on the value of isError:
1.Partial View (Views/Shared/BugModal.cshtml)
#model BugViewModel
<div class="modal fade" id="bugModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Bug Reporting Tool</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span>×</span>
</button>
</div>
<form id="myForm" asp-controller="Smarty" asp-action="SendBugReport" enctype="multipart/form-data">
<div id="result"></div>
<div class="modal-body">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
<label asp-for="FormFile" class="control-label"></label><br />
<input asp-for="FormFile" id="FormFile" name="FormFile" type="file" />
<span asp-validation-for="FormFile" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Schliessen</button>
<button type="button" id="BugReportBtn" class="btn btn-success">Bug Report senden</button>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script>
$('#BugReportBtn').on('click', function (event) {
var url = "/Smarty/SendBugReport";
var description = document.getElementById("Description").value;
var fileInput = $('#FormFile')[0];
var formFile = fileInput.files[0];
var formData = new FormData();
formData.append("Description", description);
formData.append("FormFile", formFile);
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
processData:false,
contentType: false,
success: function (data) {
if (!data.isError) {
$("#result").html("<span class='border border-success text-success'>" + data.message + "</span>");
} else {
$("#result").html("<span class='border border-danger text-danger'>" + data.message + "</span>");
}
$('#bugModal').modal('show');
}
});
});
</script>
2.Action
[HttpPost]
public async Task<JsonResult> SendBugReport(BugViewModel viewModel)
{
//Process Form
string message;
bool isError;
//set data to message and isError
return Json(new { message, isError });
}
On my login page I have a dropdownlist to change the culture of the application for which I am doing a Ajax call to set the culture. By default I have set to 'en_US'.
My issue is when I am login directly without changing the culture I am able to login successfully, but when I change the culture and tries to login, I am not able to do that. Is this happening because of AJAX call made, which makes custom attribute not registered ?
Also, my login method has a custom attribute defined. Below is the code.
AJAX Call
$('#ddlLanguages').change(function () {
var val = $('#ddlLanguages').val()
createCookie('culturecookie', val, 7);
$.ajax({
type: "POST",
url: '/Account/GetCultureNew',
data: { culturename: val },
success: function (result) {
$("#logo-group").html('');
$(document.body).html('');
$(document.body).html(result);
},
error: function (data) {
//alert('Error');
}
});
});
Ajax Method in controller
[HttpPost]
public ActionResult GetCultureNew(string culturename)
{
if (!string.IsNullOrEmpty(culturename) & culturename.Contains("#"))
{
string[] strdata = culturename.Split('#');
if (strdata.Length > 0)
{
AppTenant tenant = HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");
if (tenant != null)
{
tenant.LoggedInCulture = strdata[0];
tenant.LanguageID = Convert.ToInt32(strdata[1]);
HttpContext.Session.SetObjectAsJson("TenantInfo", tenant);
}
}
}
List<SelectListItem> items = new List<SelectListItem>();
items = HttpContext.Session.GetObjectFromJson<List<SelectListItem>>("LanguageData");
foreach (var item in items)
{
if (item.Value == culturename)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
var itemsString = JsonConvert.SerializeObject(items);
CookieOptions obj = new CookieOptions();
obj.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Append("Languagelist", itemsString, obj);
var viewModel = new LMS_User { ReturnUrl = string.Empty, LanguageList = items };
return View("Login", viewModel);
}
Login Method
[HttpPost]
[AllowAnonymous]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route("Admin/Login/{clietname}")]
public async Task<IActionResult> Login([Bind(include: "Email,Password,RememberMe")] LMS_User model, string returnUrl)
{
// my login logic
}
EDIT :- 1
Login partial View
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
<div class="well no-padding">
<form action="#Url.Action("login", "account")" method="POST" id="login-form" class="smart-form client-form">
<header>
#obj["SingnIn"]
</header>
#Html.AntiForgeryToken()
<fieldset>
<section>
<label asp-for="LanguageList">#obj["LanguageList"] </label>
#Html.DropDownList("Languages", Model.LanguageList, null, new { id = "ddlLanguages", #class = "form-control" })
</section>
<section>
<label asp-for="Email">#obj["Email"]</label>
<label class="input">
<i class="icon-append fa fa-user"></i>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i>>#obj["tooltipEmail"]</b>
<span asp-validation-for="Email" class="text-danger"></span>
</label>
</section>
<section>
<label asp-for="Password">#obj["Password"]</label>
<label class="input">
<i class="icon-append fa fa-lock"></i>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i>#obj["tooltippassword"] </b>
<span asp-validation-for="Password" class="text-danger"></span>
</label>
<div class="note">
<i class="fa fa-frown-o"></i> #obj["Forgot_password?"]
</div>
</section>
<section>
<label class="checkbox">
<input asp-for="RememberMe" />
<i></i>#obj["Remember_Me"]
</label>
</section>
<footer>
<button type="submit" class="btn btn-primary">
#obj["SingnIn"]
</button>
</footer>
</fieldset>
</form>
</div>
#{ await Html.RenderPartialAsync("_SocialMedia"); }
Edit 2:-Entire login view
<div id="content" class="container">
<div class="row">
#{ await Html.RenderPartialAsync("_LoginText"); }
#{ await Html.RenderPartialAsync("_LoginPartial"); }
</div>
</div>
However if I add location.reload() in AJAX success function, then by changing the culture I can login successfully.
Any help on this appreciated !
When you do the $(document.body).html(result);
The action part of the form goes missing. Hence it does not know where to post to.
Hope i have been of some help :)
net mvc 5 application and for this I use bootstrap because it looks fine.
I don't want to use for an input and a searchbutton the
#using (Html.BeginForm("...
Can I control the html tags without this from my controller. For example here is my index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
I want if I click on the Searchbutton I get a message with the text from the inputfield.
Here is the Controller:
public ActionResult Search(string value)
{
//listofUsers is a arraylist of all users that found^^
return View(listofUsers);
}
How I can do this? :)
Add a div to show the result:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<div class="custom-search-result"></div>
Then in a script tag or a linked js file:
$(document).ready(function () {
$('.custom-search-input').each(function () {
var sinput = $(this);
var svalue = sinput.find('input');
var sresult = sinput.next('.custom-search-result');
sinput.find('button').click(function () {
$.ajax({
url: '/ControllerName/Search?value=' + svalue.val(),
type: 'GET'
}).done(function (result) {
sresult.html(result);
});
});
});
});
This is a basic example with no error handling.
First I highly recommend reading Philip Walton (Google) - Decoupling your HTML, CSS and Javascript, it's extremely good.
Here how I would use MVC to it's full potential.
Model:
// Extensible Programming
// Using a string limits additional features
// Future proofing via a class that takes 2 minutes to create
public class GlobalSearch
{
public string SearchTerms { get; set; }
}
View:
#Model GlobalSearch
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
#using (Html.BeginForm("Search"))
{
<div class="input-group col-md-12">
#Html.TextBoxFor(m => m.SearchTerms, new {
#class="search-query form-control",
placeholder="Search" })
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search js-form-submit"></span>
</button>
</span>
</div>
}
</div>
</div>
</div>
Controller:
// Strongly Typed Class is Returned
public ActionResult Search(GlobalSearch search)
{
return View(listofUsers);
}
The following script will require this fantastic script called form2js which correctly converts any strongly-typed forms generated by MVC (arrays, lists etc) into Json that will be ModelBinded correctly.
$(document).ready(function() {
('.js-form-submit').on('click', function() {
var $form = $(this).closest('form');
var json = form2js($form);
var ajaxSettings = {
url: $form.attr('action'),
type: $form.attr('method'),
data: json,
contentType: "application/json",
}
$.ajax(ajaxSettings)
.done()
.always()
.fail();
});
});
Of course this could be easily abstract into it's own javascript class/namespace that returns the promise and reusable on any form that simply has a button with the class js-form-submit instead of continually rewriting $.ajax over and over again each time for different forms.