Description of the situation:
I have selectbox, I choose a person there (there, I download the entire list of employees from the database). I have two more fields (I would like to enter values from other columns (same row) (data of this employee))
Controller
using AppEcp.Models;
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace AppEcp.Controllers
{
public class UzytkownicyController : Controller
{
private readonly UzytkownicyDbContext _uzytkownicyContext;
public UzytkownicyController(UzytkownicyDbContext uzytkownicyContext)
{
_uzytkownicyContext = uzytkownicyContext;
}
public IActionResult GetItems(DataSourceLoadOptions loadOptions)
{
var GetMethod = _uzytkownicyContext.Uzytkownicy.Where(i => i.Firma == "Pekao Leasing").Select(i => new
{
i.Id,
i.Nazwa,
i.Departament,
i.Login
});
return Json(DataSourceLoader.Load(GetMethod, loadOptions));
}
[HttpGet]
public ActionResult GetDepartmentAndManager(string nazwaValue)
{
var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Nazwa == nazwaValue).Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.Manager
});
return Json(danePracownika);
}
}
}
I tried:
cshtml page
#(Html
.DevExtreme()
.SelectBox()
.ID("Id_name")
.DataSource(d => d
.Mvc()
.Controller("Uzytkownicy")
.Key("Id")
.LoadAction("GetItems")
)
.DisplayExpr("Nazwa")
.ValueExpr("Id")
.SearchEnabled(true)
.OnValueChanged("getDepAndMan")
)
#(Html.DevExtreme().TextBox()
.ID("Id_department"))
#(Html.DevExtreme().TextBox()
.ID("Id_manager"))
<script type="text/javascript">
function getDepAndMan() {
var nazwaValue = document.getElementById("Id_name").value;
$.ajax({
type: "GET",
url: '#Url.Action("GetDepartmentAndManager", "Uzytkownicy")',
contentType: 'application/json; charset=utf-8',
data: { nazwaValue : nazwaValue},
dataType: "json",
success: function (data) {
document.getElementById("Id_department").value = (data.UserDepartament);
document.getElementById("Id_manager").value = (data.UserManager);
},
error: function () {
alert("bad code noob");
}
});
}
</script>```
Do not work:
The code does not throw an error, but does not enter the downloaded data into text boxes
Access the required widget using its "options" api (refer to this demo), for example:
success: function (data) {
alert(data.UserDepartament + " " + data.UserManager);
//document.getElementById("Id_department").value = (data.UserDepartament);
//document.getElementById("Id_manager").value = (data.UserManager);
$("#Id_department").dxTextBox("instance").option("value", data.UserDepartament);
$("#Id_manager").dxTextBox("instance").option("value", data.UserManager);
}
Related
I have this code that is not running in asp.net core 3.1 I need to send a variable to the method GetClientCaseType() it give error in #Model.GetClientCaseType[myInt] myInt if i put 1 or any number it works fine while for variable it give error
function casetype(value)
{
var myInt = parseInt(value.options[value.selectedIndex].value);
var casetype |"= '#Model.GetClientCaseType[myInt]';
alert(casetype + ' = ' + myInt.toString());
$("#ClientCase_cCaseType").val(casetype);
}
in .cs page
public string GetClientCaseType(int? myInt)
{
return something;
}
Any Solution please help thanks in advance
I tried ajax with no result 'error'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebLawyer1.Data;
using WebLawyer1.Models;
namespace WebLawyer1.Pages.ClientCases
{
public class CreateModel : PopulateClientCasePageModel
{
private readonly WebLawyer1.Data.LawyerDbContext _context;
public CreateModel(WebLawyer1.Data.LawyerDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateClientInfosDropDownList(_context);
PopulateCaseTypesDropDownList(_context);
return Page();
}
[BindProperty]
public ClientCase ClientCase { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
//_context.ClientInfo.Add(ClientInfo);
//await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
var emptyClientCase = new ClientCase();
if (await TryUpdateModelAsync<ClientCase>(
emptyClientCase,
"clientcase", // Prefix for form value.
s => s.iClientInfoID, s => s.iCaseTypeID, s => s.cCaseType, s => s.cPart,
s => s.iSequence, s => s.cKeyCase, s => s.dDate, s => s.cTitle,
s => s.cNote, s => s.cDetail, s => s.nFees, s => s.lWinFail, s => s.lClosed))
{
_context.ClientCase.Add(emptyClientCase);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
// Select CategoryID if TryUpdateModelAsync fails.
PopulateClientInfosDropDownList(_context, emptyClientCase.iClientInfoID);
PopulateCaseTypesDropDownList(_context, emptyClientCase.iCaseTypeID);
return Page();
}
public ActionResult GetUploadedFile(int id)
{
var result = _context.CaseType.Where(x => x.iCaseTypeID == id).First();
return Json(result.cCaseType);
}
}
}
<script>
function casetype(value) {
var id = parseInt(value.options[value.selectedIndex].value);
$.ajax({
url: '#Url.Action("GetUploadedFile", "Create")',
type: "POST",
data: JSON.stringify(id),
contentType: "application/json",
datatype: "json",
success: function (data) {
if (data != null) {
var vdata = data;
$('#ClientCase_cCaseType').val(vdata.id);
}
}
});
}
</script>
Actually, you can't do this. The reason is that they do not "live" in the same time. Javascript code is available only after C# / Razor is rendered. Refer to this thread.
So, I think you should use ajax here to send a request to access GetClientCaseType() method.
Update:
For how to send a ajax post request, you need to do the below steps:
1.Add the below service in stratup.cs
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
2.Add the AntiForgeryToken to the current page
#Html.AntiForgeryToken();
3.Set the token to request header in ajax
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
This is an example:
Create.cshtml:
#page
#model RazorApp.Pages.ClientCases.CreateModel
#Html.AntiForgeryToken();
<button id="btn" onclick="casetype()">Click</button>
#section scripts{
<script>
function casetype() {
var id = 1;
$.ajax({
url: 'Create?handler=GetUploadedFile',
type: "POST",
data: { id : id },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
if (data != null) {
var vdata = data;
}
}
});
}
</script>
}
Create.cshtml.cs:
public class CreateModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostGetUploadedFile(int id)
{
var result = "AAA";
return new JsonResult(result);
}
}
Note: the pagehandler should be in this format OnPostXxx() or OnGetXxx().
And the url in ajax should like XXX?handler=Xxx.
Result:
I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).
i have a modal with input, i digit some emails and add to a list, later i want to pass this list of emails to my function that send emails.
var listEmails = [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
listEmails.push(text);
}
document.getElementById("sendEmail").onclick = function () {
#*location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails='+listEmails;
}
that is my function in Controller that receive a list of email to send
public void TestSendReport(List<string> ListMails)
Please try below code and try to call controller method using jQuery Ajax
var list= [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
list.push(text);
}
document.getElementById("sendEmail").onclick = function () {
var jsonText = JSON.stringify({ list: list});
$.ajax({
type: "POST",
url: "ProductMarketplace/TestSendReport",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("success"); },
failure: function() { alert("failed"); }
});
}
And use controller method like this,
[WebMethod]
public void TestSendReport(List<string> list)
{
}
document.getElementById("sendEmail").onclick = function () {
location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails=' +
encodeURI(JSON.stringify(listEmails));
}
public void TestSendReport(List<string> emails)
{
}
I have a form in my view which has only one textarea input initially and user can add more textarea inputs if he wants with jquery. My problem is related to second case. After submitting the form i am getting an array of objects in console but when i am passing this array to mvc action in my controller it is coming to be null.
I have tried these solution but did not succeed:
Send array of Objects to MVC Controller
POST a list of objects to MVC 5 Controller
here is my code:-
jquery code:
$('body').on('submit', '#addTextForm', function () {
console.log($(this));
var frmData = $(this).serializeArray();
console.log(frmData);
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify({ obj: frmData }),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
MVC action:
[HttpPost]
public string UploadText(SliderTextList obj)
{
return "success";
}
my object class:
public class SliderText
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("SlideName")]
public string SlideName { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
public class SliderTextList
{
public List<SliderText> AllTexts { get; set; }
}
I have to store the Content in json file with Id and SlideName, so i think i have to pass a list object in mvc action Uploadtext which is coming out to be null always. Please help.
$(document).ready(function(){
$('body').on('submit', '#addTextForm', function () {
var listData=[];
var oInputs = new Array();
oInputs = document.getElementsByTag('input' );
var k=1;
for ( i = 0; i < oInputs.length; i++ )
{
if ( oInputs[i].type == 'textarea' )
{
var obj=new Object();
obj.Id=k;
obj.SlideName=oInputs[i].Name;
obj.Content=oInputs[i].Value;
K=parseInt(k)+1;
listData.push(obj);
}
}
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify(listData),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
});
Since the sever side expects a string as argument obj as a query string I think this is what you need.
data: {
obj: JSON.stringify(frmData)
},
as an alternative using as Stephen suggested on the comments
data: {
obj: $('#addTextForm').serialize()
},
Wellcome!
I have a problem with passing data from JavaScript to MVC Controller. Im new to MVC so I probably miss something.
$("#example").keypress(function (event) {
var data = "example";
$.ajax({
url: "/example/example",
type: "POST",
dataType: "json",
data: { example: data },
success: function (example) {
var items = "";
$.each(data, function (i, example) {
items += "<option>" + example + "</option>";
});
$("#example").html(items);
}
});
});
public class PeoplePickerController : BaseController
{
// GET: PeoplePicker
public ActionResult PeoplePicker(object data)
{
if (HttpContext.Request.IsAjaxRequest())
{
IQueryable logins = (IQueryable)QueryDatabaseForUsersAndGroups((string)data, Context.Users);
return Json(new SelectList(example, "example"), JsonRequestBehavior.AllowGet);
}
return PartialView();
}
}
data parameter is always null.