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:
Related
I'm having error when creating an object in javascript
I'm having this generic error:
Uncaught SyntaxError: Invalid or unexpected token
That's why i can't solve it. it didn't have specific error message.
This is my model
[Serializable, JsonObject]
public class CompleteOrderRequest : BaseMessageRequest<CompleteOrderRequestDto>
{
}
[Serializable]
[JsonObject, Bind("RequestFrom,RequestBy")]
public abstract class BaseMessageRequest<T> : IBaseMessageRequest<T> where T : class, new()
{
protected BaseMessageRequest()
{
Request = new T();
}
[Required, StringLength(255, MinimumLength = 3)]
[BindProperty(SupportsGet = true), BindRequired]
[FromQuery]
public string RequestBy { get; set; }
[BindProperty(SupportsGet = true)]//, BindRequired]
[FromQuery]
public T Request { get; set; }
}
public class CompleteOrderRequestDto
{
public string OrderNo { get; set; }
}
This is my controller
public async Task<IActionResult> PayNow([FromBody] CompleteOrderRequest request)
{
return View();
}
And this is my javascript code.
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow/${CompleteOrderRequest}',
success: function (data) {
if (data.success) {
}
}
});
The error is in this line. I'm encountering error before calling the controller.
CompleteOrderRequest.RequestBy = 'test';
So what's wrong with what Am i doing? And I'm receiving this error
Uncaught SyntaxError: Invalid or unexpected token
When creating your object in JavaScript, you can declare the properties inline like this:
var CompleteOrderRequest = {
RequestBy: "test"
};
You'd also need to ensure you provide that object as the data parameter when posting with ajax.
fix the ajax
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: { request: CompleteOrderRequest}
success: function (result) {
if (result.success) {
}
}
});
and when you use only one kind of data from ajax , you don't usually need [FromBody]. Try to change the action too
public async Task<IActionResult> PayNow(CompleteOrderRequest request)
Since you use [FromBody] in action,you need to change your contentType to application/json and convert CompleteOrderRequest to json type:
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: JSON.stringify(CompleteOrderRequest),
contentType:"application/json",
success: function (data) {
if (data.success) {
}
}
});
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);
}
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 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()
},
I have a partial that I refresh via Ajax.
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
}
});
}
});
Refresh action:
[HttpPost]
public ActionResult Refresh(int id)
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
This works well, except that when an error (such as an HTTP exception) occurs, the error view is sent to the partial when I want it to be shown as the main view.
Error action:
public ActionResult Error(string message)
{
ViewBag.Message = message;
return View();
}
I have tried using Javascript (both in the view and returned by the controller) to redirect the browser, however both are buggy and I assume bad practice.
Try as
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
},
error: function(result){
//call new action
}
});
}
});
Assuming Error() returns a complete view (with layout and script/css), you could always try completely overwriting your document:
success: function (result) {
$('#partialHolder').html(result);
},
error: function(xhr) {
if(xhr.responseText) {
var newDoc = document.open("text/html", "replace");
newDoc.write(xhr.responseText);
newDoc.close();
}
}
This will effectively overwrite your entire dom and will cause you to lose everything that was on the page.
Credits for document rewrite to this answer
Try something like this
in your action
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return PartialView("~/Views/PartialView.cshtml", null);
}
}
so in your ajax success
if (result != null) {
//do your stuff
} else {
// the controller action returned a partial
$('#divInYourMain').html("Error 123");
}
I managed to solve this in a similar way to theLaw's answer, by using a try/catch block and the Content helper method to return a simple string which triggers a redirect.
Refresh Action:
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return Content("error");
}
}
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
if (result == "error") {
location.replace("#Url.Action("General", "Error")");
}
else {
('#partialHolder').html(result);
}
}
});
}
});