I am saving data of how long users hold the buttons when they are writing. Now the data is saved in
const holdingTimes, but I want to add any button in html like SAVE and then send data from js to my JavaController.
html:
<div class="container">
<p>Write some text:</p>
<form>
<div class="form-group">
<textarea class="form-control" rows="5" id="myInput"></textarea>
</div>
</form>
</div>
js:
<script>
var pressedTime; var releasedTime; var holdingTime;
const holdingTimes = [];
document.getElementById("myInput").addEventListener("keydown", pressedFunction);
document.getElementById("myInput").addEventListener("keyup", releasedFunction);
function pressedFunction() {
pressedTime = Date.now();
}
function releasedFunction() {
releasedTime = Date.now() ;
holdingTime = releasedTime - pressedTime;
holdingTimes.push(holdingTime);
}
</script>
Any ideas how to build JavaController and SAVE button?
JavaController looks like:
#Controller
#Scope(WebApplicationContext.SCOPE_SESSION)
#RequestMapping("/getValues")
public class JavaController {
int [] holdingTimes;
#RequestMapping("/save")
public String getData(int[] holdingTimesFromJs, Model model) {
holdingTimes = holdingTimesFromJs;
return "redirect:/";
}
}
On click of button, call a Javascript function which will send an Ajax POST request to the Controller.
JavaScript Code:
const holdingTimes = [];
holdingTimes.push(10);
holdingTimes.push(20);
holdingTimes.push(30);
$.ajax({
'url' : "/test-url",
"data" : JSON.stringify(holdingTimes),
'method' : "POST",
'contentType' : 'application/json'
}).done(function(data) {
// handling code for success response
});
Spring Controller:
#PostMapping("/test-url")
public String testArrayUpload(#RequestBody int[] times) {
//your logic goes here
return "test";
}
Related
I have controller for changing website language, saving cookie and returning url.
`
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
namespace Website.Controllers;
public class CultureController : Controller
{
[HttpPost]
public IActionResult SetCulture(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) }
);
return LocalRedirect(returnUrl);
}
}
`
And in View I need create html list for better user experience but I don't understand how to change from 'form' to 'list' or how to submit changes and return url
`
#using Microsoft.AspNetCore.Localization
#using Microsoft.Extensions.Options
#inject IOptions<RequestLocalizationOptions> LocalizationOptions
#{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocalizationOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.EnglishName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";
}
<!-- FROM FORM -->
<div class="language">
<form asp-controller="Culture" asp-action="SetCulture" asp-route-returnUrl="#returnUrl" class="form-horizontal nav-link text-dark">
<select name="culture"
onchange="this.form.submit();"
asp-for="#requestCulture.RequestCulture.UICulture.Name"
asp-items="cultureItems">
</select>
</form>
</div>
<!-- TO LIST -->
<div class="language-toggle">
<i class="fas fa-language"></i>
<ul class="language-menu">
#foreach (var item in LocalizationOptions.Value.SupportedUICultures)
{
<li>#item.Name.ToUpper()</li>
}
</ul>
</div>
`
I tried with anchor tag helper but without success
output
Output
I can get current url in view and append ?culture=en and that changes language and stays on current page but does not save cookie so every time user goes to different page website is in native language not in user selected language.
You can achieve that with something like this:
<head>
<script type="text/javascript">
function submitCulForm(val) {
document.getElementById("cultureVal").value = val;
var hh = document.getElementById("cultureForm");
hh.submit();
return false;
}
</script>
</head>
Then
<form asp-controller="Culture" id="cultureForm" asp-action="SetCulture" asp-route-returnUrl="#returnUrl" class="form-horizontal nav-link text-dark">
<input id="cultureVal" type="hidden" name="culture" value="-">
<div class="language-toggle">
<i class="fas fa-language"></i>
<ul class="language-menu">
#foreach (var item in LocalizationOptions.Value.SupportedUICultures)
{
<li>#item.Name.ToUpper()</li>
}
</ul>
</div>
</form>
If you try to pass the value with herf,you shouldn't add [HttpPost] Attribute on your controller.
I tried with the codes in your controller,it works well,I'll show what I've tried and hopes it could help
in View:
<div>
<a asp-action="SetCulture" asp-route-culture="zh-CN">zh-CN</a>
<a asp-action="SetCulture" asp-route-culture="en-US">en-US</a>
</div>
<script>
var cookie = document.cookie
console.log(cookie)
</script>
in Controller:
public IActionResult SetCulture(string culture)
{
if (culture != null)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) });
return RedirectToAction("Create");
}
return BadRequest();
}
Configure in startup:
services.AddControllersWithViews()
.AddDataAnnotationsLocalization(
options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResources));
});
...............
var supportedCultures = new[] { "en-US", "zh-CN" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
created an empty class called SharedResources
and the resourcefile:
The Result:
It just performed as the document,and if you tried with mulipule providers,you could try to change request culture providers order which has been mentioned in the document
I'm just learning about MVC and a problem I've run into is passing a list of models to a controller. I have AutomationSettingsModel, which contains a list of AutomationMachines. I've successfully populated a table in my view with checkboxes bound to data in AutomationMachines. However, passing the data to a method in the controller is turning out to be harder than I expected.
Here is my view with the first attempt at passing the data:
#model FulfillmentDashboard.Areas.Receiving.Models.Automation_Settings.AutomationSettingsModel
<div class="container-fluid px-lg-5">
#using (Html.BeginForm("Index", "ReceiverSettings", "get"))
{
<div>
<h2>Receiving Automation Settings</h2>
<br>
<table id="machineSettings" class="table">
<tr>
<th>Automation Machine Name</th>
<th>Divert Line Setting </th>
</tr>
#if (Model.AutomationMachines != null && Model.AutomationMachines.Count > 0)
{
foreach (var item in Model.AutomationMachines)
{
<tr>
<td> #Html.DisplayFor(x => item.Name) </td>
<td> #Html.CheckBoxFor(x => item.DivertSetting) </td>
</tr>
}
}
</table>
<div class="row">
<input class="btn btn-primary" type="button" value="Save"
onclick="location.href='#Url.Action("UpdateDivertSettings", "ReceiverSettings", new { models = #Model.AutomationMachines } )'" />
</div>
</div>
}
</div>
This resulted in UpdateDivertSettings being hit in my controller, but the data was null. After some searching, it looks like I will need to use Ajax, which I am unfamiliar with. I tried following the example at this site, which resulted in the following addition to the view:
<input type="button" id="btnSave" value="Save All" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var machines = new Array();
$("#machineSettings TBODY TR").each(function () {
var row = $(this);
var machine = {};
machine.Name = row.find("TD").eq(0).html();
machine.DivertSetting = row.find("TD").eq(1).html();
machines.push(machine);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/ReceiverSettings/UpdateDivertSettings",
data: JSON.stringify(machines),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
</script>
However that never seemed to hit UpdateDivertSettings in the controller. Some more searching resulting in the idea of serializing my AutomationSettingsModel and passing that via Ajax, but I'm not really sure how to do that. It also looks like I can do something using Ajax.BeginForm, but I can't figure out how I would structure the new form. So I'm trying to get some input on the easiest way to get this data to my controller.
Edit:
Here is the controller as it currently stands:
namespace FulfillmentDashboard.Areas.Receiving.Controllers
{
[RouteArea("Receiving")]
public class ReceiverSettingsController : BaseController
{
private readonly AutomationService automationService;
public ReceiverSettingsController(AutomationService _automationService)
{
automationService = _automationService;
}
[Route("ReceiverSettings/Index")]
public async Task<ActionResult> Index()
{
var refreshedView = await automationService.GetAutomationSettings( new AutomationSettingsModel(ActiveUserState.ActiveIdSite) );
refreshedView.AutomationMachineIdSite = ActiveUserState.ActiveIdSite;
return View("Index", refreshedView);
}
public async Task<ActionResult> UpdateDivertSettings(List<AutomationMachineModel> machines)
{
//foreach (AutomationMachineModel machine in machines)
//{
// var results = await automationService.UpdateAutomationSettings(machine, ActiveUserState.IdUser);
//}
return Json(new { #success = true });
}
}
}
First time with MVC5 and Telerik... I am reading Active Directory and getting all the security groups to display in a TreeView. After an Admin is done selecting the Roles he/she shall press the Save Groups button and then the javascript is supposed to get all nodes and pass them to the controller. The controller will save to the database. I need to know how to access the datacontext for a given node. After I get the data context I can proceed to get all of the nodes context and pass it to the controller.
Kendo Treeview and Buttons:
#{
ViewBag.Title = "Configure";
}
#model IEnumerable<CMDB.Web.Models.AdminGroups>
<div>
<input id="save" type="button" value="Save Groups" onclick="SaveData()" />
<input id="return" type="button" value="Return" onclick="location.href='#Url.Action("Index", "Admin")'" />
#(Html.Kendo().TreeView()
.Name("treeview")
.Checkboxes(checkboxes => checkboxes
.Name("checkedFiles")
.CheckChildren(true)
)
.Events(events => events.Check("onCheck"))
.DataTextField("Name")
.AutoScroll(true)
.DataSource(source => source
.Model(model => model.Id("id").HasChildren("hasChildren"))
.Read(read => read.Action("GetActiveDircetoryGroups", "Configure"))
)
)
</div>
Javascript:
<script type="text/javascript" >
//show checked node IDs on datasource change
function onCheck() {
var treeView = $("#treeview").data("kendoTreeView");
var id = treeView.dataItem(e.node);
}
function SaveData() {
var AllSelectedNodes = new Array();
AllSelectedNodes = ($("#treeview .k-item input[type=checkbox]:checked").closest(".k-item"));
alert(AllSelectedNodes.join('\n'));
var myApiUrl = '#Url.HttpRouteUrl("DefaultAPI", new { controller = "AdminValues", action = "SaveSelectedAdmins"})';
var movies = $.ajax({
url: myApiUrl,
type: 'POST',
data: AllSelectedNodes
});
}
</script>
Controller:
[HttpPost]
public void SaveSelectedAdmins(IEnumerable<CMDB.Web.Models.AdminGroups> ag)
{
string Sids = string.Empty;
foreach (var s in ag)
{
var pc = new PrincipalContext(ContextType.Domain, "", "");//blank for security purposes
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Guid, s.id.Value.ToString());
if (s.id.Value.ToString() == gp.Guid.Value.ToString())
{
Sids = Sids + "," + gp.Sid;
}
}
using (var ctx = new Data.DBContext())
{
var d2 = (from d in ctx.Set<Entities.Config>()
where d.Property == "str"
select d).SingleOrDefault();
d2.Value = Sids;
ctx.SaveChanges();
}
}
Using $.post instead of $.ajax fixed the issue.
I am trying to update the multiple partial view using Jquery , MVC and Json .
My partial views are not updating
Here is my code
My View code is
#model DropdownGrid.Models.MyMultipleUpdateViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
<script type="text/javascript">
function _Complete(data) {
var JsonObj = $.parseJSON(data.responseText);
alert(JsonObj);
alert(JsonObj.myTest1ViewModel.MyTestUpdate)
alert(JsonObj.myTest2ViewModel.MyTestUpdate)
$("#Div1").html(JsonObj);
$("#Div2").html(JsonObj);
}
</script>
<br>
<br>
<br>
<br>
<fieldset>
<div id="Div1">
#{ Html.RenderPartial("_MyTest1PartialView", Model); }
</div>
<div id="Div2">
#{ Html.RenderPartial("_MyTest2PartialView", Model); }
</div>
</fieldset>
<fieldset>
#using (Ajax.BeginForm("CreateStudent", "GetStudents",
new AjaxOptions { HttpMethod = "Post", OnComplete = "_Complete" }))
{
<input type="submit" value="Submit" />
}
</fieldset>
My Controller code is
enter code here
public class GetStudentsController : Controller
{
public ActionResult Index()
{
MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
obj.myTest1ViewModel = new MyTest1ViewModel();
obj.myTest1ViewModel.MyTestUpdate = "Test1";
obj.myTest2ViewModel = new MyTest2ViewModel();
obj.myTest2ViewModel.MyTestUpdate = "Test2";
return View(obj);
}
[HttpPost]
public ActionResult CreateStudent(MyMultipleUpdateViewModel objuserloginmodel)
{
MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
obj.myTest1ViewModel = new MyTest1ViewModel();
obj.myTest1ViewModel.MyTestUpdate = "Test1"+DateTime.Now.ToString();
obj.myTest2ViewModel = new MyTest2ViewModel();
obj.myTest2ViewModel.MyTestUpdate = "Test2" + DateTime.Now.ToString();
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
And My View model is
public class MyTest1ViewModel
{
public string MyTestUpdate;
}
public class MyTest2ViewModel
{
public string MyTestUpdate;
}
public class MyMultipleUpdateViewModel
{
public MyTest1ViewModel myTest1ViewModel;
public MyTest2ViewModel myTest2ViewModel;
}
It is not working
Could you please help me to resolve my issue.
From your Action method, you are returning a JSON structure like this
{
"myTest1ViewModel": {
"MyTestUpdate": "Test112/12/2015 5:04:57 PM"
},
"myTest2ViewModel": {
"MyTestUpdate": "Test212/12/2015 5:04:57 PM"
}
}
But in your code, you are trying to pass the json object to the html method. you are ideally supposed to pass some html markup to html method.
Since you are having a Json object, you should read the properties of the json object and explicitly set each and every element markup, provided your partial view has items with unique ids.
Assuming your partial view looks like this
#model MyMultipleUpdateViewModel
<div id="testUpdate">#Model.myTest1ViewModel.MyTestUpdate </div>
Inside your javascript method, you can set the markup on the div.
function _Complete(data) {
var JsonObj = $.parseJSON(data.responseText);
$("#testUpdate").html(JsonObj.myTest1ViewModel.MyTestUpdate);
// You may set other properties as well.
}
I'm trying to make a list of items (telephones and dependents for a customer), for example, the user could include some number phones and remove others (maybe edit them if it is possible), like a list inside the record of customer.
I'd like to know how can I do it on client side and get the list in server side ?
Is there a jquery plugin or a best pratice to do it?
P.S.: I'm using ASP.Net MVC 2.
Serialise the data into a format like JSON and then send it to the server as a string.
When I had to learn it, these posts were extremely useful.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
You can serialise a javascript array into a string that ASP.Net can deserialise.
There is a standard called JSON which is good, as it adds nearly no noise on the actual data (like xml does, incrementing a LOT the amount of data to transfer).
You can then use the $.ajax jquery method to send this data to a WebMethod you created (see links) and get an understandable response back.
EDIT:
If you were already inside this stuff, you can simply use the JSON.stringify() method, passing the object/array to serialise in it.
I keep this example around to get me started, just put the proper stuff in the proper files and edit it to match what you are doing:
/* in this case I am using */
available at: http://www.json.org/js.html
function jsonObject()
{
};
var phoneListObject = new jsonObject();
function SaveJsonObject()
{
phoneListObject.Control = new jsonObject();
phoneListObject.Control.CustomerId = $("#CustomerId").val();
phoneListObject.Control.CustomerName = $("#CustomerName").val();
phoneListObject.ListBody.PhonesBlock = new jsonObject();
phoneListObject.ListBody.PhonesBlock.Phone = new Array();
$('#PhonesBlock .Phone').each(function(myindex)
{
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
});
};
$(function()
{
function SaveCurrentList()
{
SaveJsonObject();
var currentSet = phoneListObject;
var formData = { FormData: currentSet };
phoneListJSON = JSON.stringify(formData);
var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
SavePhoneListData(FormData);
};
function SavePhoneListData(phonesData)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: phonesData,
dataFilter: function(data)
{
var msg;
if ((typeof (JSON) !== 'undefined') &&
(typeof (JSON.parse) === 'function'))
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "../../WebServices/ManagePhones.asmx/SaveJson",
success: function(msg)
{
SaveSuccess(msg);
},
complete: function(xhr, textresponse)
{
var err = eval("(" + xhr.responseText + ")");
},
error: function(msg)
{
},
failure: function(msg)
{
}
});
};
$('#btnSave').click(function()
{
SaveCurrentList();
});
});
/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}
/XML of the form data:/
<FormData>
<Control>
<CustomerId>12345y6</CustomerId>
<CustomerName>Joe Customer</CustomerName>
</Control>
<PhonesBlock>
<Phone>
<PhoneNumber>234-233-2322</PhoneNumber>
<PhoneName>son harry</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2323</PhoneNumber>
<PhoneName>son frank</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2321</PhoneNumber>
<PhoneName>momk</PhoneName>
</Phone>
</PhonesBlock>
</FormData>
/* form layout snip */
<div class="control">
<div class="customer">
<input typeof="text" id="CutomerId" />
<input typeof="text" id="CutomerName" />
</div>
<div class="phoneslist" id="PhonesBlock">
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
</div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />
signature of the web service method:
[WebMethod(EnableSession = true)]
public string SaveJson(string FormData)
{
}