I am getting error below while using ajax in asp.net MVC, and I have no idea what's wrong with it!
JavaScript critical error at line 161, column 101 in
http://localhost:50474/Home/Products\n\nSCRIPT1006: Expected ')'
Here is my View:
<p class="text-center"><a class="btn btn-primary" onclick="CreateOrder(#pr.ProId)" role="button">خرید</a>
Here my Action in controller:
[HttpPost]
public ActionResult CreateOrder(Guid productId)
{
Order or = new Order();
or.Number = 1;
or.ProductId = productId;
or.SessinId = Request.UserHostAddress;
int proprice = db.Products.Where(c => c.ProId == productId).Select(c => c.Price).FirstOrDefault();
or.TotalPrice = proprice * 1;
db.Orders.Add(or);
db.SaveChanges();
int count = (db.Orders.Where(c => c.SessinId == or.SessinId).Select(c =>
c.OrderId)).Count();
Session["ShopcartCount"]= count;
db.Dispose();
return RedirectToAction("Products", "Home");
}
And here is ajax code:
<script>
function CreateOrder(productId) {
$.ajax({
url: "/Home/CreateOrder/" + productId,
type: "post"
}).done(function (result) {
$("#shopcart").html(result);
});
}
$(function () {
$("#shopcart").load("/Home/ShopCartCount");
});
</script>
Please check this way you got this error
Here working example first button your code and second button working fine.
Click here
View
<p class="text-center"><a class="btn btn-primary" onclick="CreateOrder('#pr.ProId')" role="button">خرید</a>
Like #jishan siddique posted in his answer, you need to use single quotes ' ' around your model property '#pr.ProId' like CreateOrder('#pr.ProId)' instead of CreateOrder(#pr.ProId) for the Razor view to recognise it.
Related
I want receive object list using thymeleaf in javascript.
I am studying spring boot Please help me.
error message like below.
Multiple annotations found at this line:
- ',' expected.
<script>
/*<![CDATA[*/
let team=[[${teamMemberList.userid}]];
alert(team);
/*]]>*/
</script>
controller
#GetMapping(value = "/detail.do")
public String openPostDetail(#ModelAttribute("params") PostDTO params, #RequestParam(value = "pnum", required = false) Long pnum, Model model) {
PostDTO postDTO = postService.getPostDetail(pnum);
if (postDTO == null || "Y".equals(postDTO.getDeleteyn())) {
return "redirect:/main.do";
}
List<CommentDTO> commentList= commentService.getCommentList(pnum);
List<UserDTO> teamMemberList = teamMemberService.getTeamMembertList(pnum);
model.addAttribute("postDTO", postDTO);
model.addAttribute("commentList", commentList);
model.addAttribute("comment", new CommentDTO());
model.addAttribute("teamMemberList", teamMemberList); //this
model.addAttribute("teamMember", new UserDTO());
int countMember = teamMemberService.selectTeamMemberTotalCount(pnum);
model.addAttribute("countMember", countMember+1);
if (countMember >= postDTO.getMinpeople()){
model.addAttribute("minpeople", true);
System.out.println(countMember);
}
return "/detail";
}
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";
}
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 });
}
}
}
In a MVC partial view file, I build one Html.TextBox and two submit buttons. These two buttons will increase/decrease the Html.TextBox value once clicked. The Html.TextBox displayed value will change accordingly.However, once I need to update the #refTable div based on the new value after click. The page or section never updated. Codes are below, where some comments are added for explanation purpose. Thanks for your help.
//******* cshtml file **********//
<body>
</body>
<input type="submit" value="PrevY" name="chgYr2" id="pY" />
#{
var tempItem3 = Model.First(); // just give the first entry from a database, works.
if (ViewData["curSel"] == null)
{
#Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
ViewBag.selYear = Convert.ToDateTime(tempItem3.Holiday_date).Year; // just initial value, works
ViewData["curSel"] = Convert.ToDateTime(tempItem3.Holiday_date).Year;
}
else
{
#Html.TextBox("yearSelect3", ViewData["curSel"].ToString());
}
}
<input type="submit" value="NextY" name="chgYr2" id="nY" />
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", "#nY", function () {
var val = $('#yearSelect3').val();
$('#yearSelect3').val((val * 1) + 1);
var dataToSend = {
id: ((val * 1) + 1)
}
// add some jquery or ajax codes to update the #refTable div
// also ViewBag.selYear need to be updated as ((val * 1) + 1)
// like: ViewBag.selYear = ((val * 1) + 1);
// any similar temp variable is fine
});
});
$(document).on("click", "#pY", function () {
var val = $('#yearSelect3').val();
$('#yearSelect3').val((val * 1) - 1);
var dataToSend = {
id: ((val * 1) - 1)
}
});
});
</script>
<span style="float: right">Set Holiday Calender for 2013</span>
<span id="btnAddHoliday">#Html.ActionLink("Add Holiday", "Create", null, new { id = "addHilBtn" })</span>
<div id="refTable">
<table class="tblHoliday" style="width: 100%;">
<th>
Holiday
</th>
<th>
Dates
</th>
<th>Modify</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
if ( Convert.ToDateTime(item.Holiday_date).Year == ViewBag.selYear)
// if the ViewBag.selYear is hard code, this selection "works"
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Holiday_Name)
</td>
<td>
#item.Holiday_date.Value.ToString("MM/dd/yyyy")
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { })
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { })
</td>
</tr>
}
}
</table>
</div>
You'll need AJAX if you want to update a part of your page without reloading the entire page.
main cshtml view
<div id="refTable">
<!-- partial view content will be inserted here -->
</div>
#Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>
<script>
$(document).ready(function() {
$("#pY").on("click", function() {
var val = $('#yearSelect3').val();
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
});
});
</script>
You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.
The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.
HolidayController Update action
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.
view model
public class HolidayViewModel
{
IEnumerable<DateTime> Dates { get; set; }
}
HolidayPartialView.csthml
#model Your.Namespace.HolidayViewModel;
<table class="tblHoliday">
#foreach(var date in Model.Dates)
{
<tr><td>#date.ToString("MM/dd/yyyy")</td></tr>
}
</table>
This is the stuff that gets inserted into your div.
The main concept of partial view is returning the HTML code rather than going to the partial view it self.
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
this action return the HTML code of the partial view ("HolidayPartialView").
To refresh partial view replace the existing item with the new filtered item using the jQuery below.
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
You can also use Url.Action for the path instead like so:
$.ajax({
url: "#Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
I know there are many questions/tutorials for this subject, but cannot solve my problem.
I have to ask for your help. Second day cannot find out the solution to this simple problem.
I am trying as in this tutorial - http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/cascading-dropdownlist-in-Asp-Net-mvc/
That is working fine, but once i try from DB, i am getting error "Uncaught ReferenceError: data is not defined"
Here is my web page
#model testEmpty.Models.Address
#{
ViewBag.Title = "Create";
}
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/myScripts/myScripts.js"></script>
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group col-md-10">
#Html.Label("Zone")
#Html.DropDownList("ZoneId", ViewBag.ZoneName as SelectList, "--Select a Zone--", new { id = "ZoneId" })
#Html.ValidationMessage("Zone", "*")
</div>
<div class="form-group">
<div class="col-md-10">
#Html.Label("Districts of SZ")
<select id="DistrictSZ" name="DistrictSZ"></select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
private myContext db = new myContext();
// GET: Addresses
public ActionResult Index()
{
var zones = db.Addresses.Include(a => a.Zone);
ViewBag.ZoneName = new SelectList(zones, "Value", "Text");
return View(zones.ToList());
}
public JsonResult DistrictList(int id)
{
var district = from s in db.Districts
where s.ZoneId == id
select s;
return Json(new SelectList(district.ToArray(), "ZoneId", "Name"), JsonRequestBehavior.AllowGet);
}
Script
$(function () {
$('#ZoneId').change(function () {
$.getJSON('DistrictList/' + $('#ZoneId').val(), getDistricts (data));
});
});
function getDistricts(data) {
var items = '<option>Select a District</option>';
$.each(data, function (i, district) {
items += "<option value='" + district.Value + "'>" + district.Text + "</option>";
});
$('#DistrictSZ').html(items);
}
As i understand, my problem is with JSON. what am I doing wrong?
Firstly you do not need to return a SelectList (javascript knows nothing about a c# class)
public JsonResult DistrictList(int id)
{
var district = db.Districts.Where(d => d.ZoneId == id).Select(d => new
{
Value = d.ZoneId, // this look wrong - see note below
Text = d.Name
});
return Json(district, JsonRequestBehavior.AllowGet);
}
Then in your script
var url = '#Url.Action("DistrictList")'; // ensure your url's are properly generated
var districts = $('#DistrictSZ'); // cache it
$('#ZoneId').change(function () {
$.getJSON(url, { id: $(this).val() }, function (data) {
districts.empty(); // remove existing options
districts.append($('</option>').val('').text('Select a District'));
$.each(data, function (i, district) {
districts.append($('</option>').val(district.Value).text(district.Text));
});
});
});
In fact, since ZoneId is always the same, you could just return a collection of the Name values
var district = db.Districts.Where(d => d.ZoneId == id).Select(d => d.Name);
and
$('#ZoneId').change(function () {
var zoneID = $(this).val();
$.getJSON(url, { id: zoneID }, function(data) {
districts.empty(); // remove existing options
districts.append($('</option>').val('').text('Select a District'));
$.each(data, function (i, district) {
districts.append($('</option>').val(zoneID).text(district));
});
});
});
However your code is generating all options with the same value (ZoneId) which does not make much sense, so I suspect you really want to use another property of District - i.e. its Id (or DistrictId?) property.
You're passing the returned value of getDistricts to the callback variable of $.getJSON.
$.getJSON('DistrictList/' + $('#ZoneId').val(), getDistricts (data));
You need to pass the function reference like this
$.getJSON('DistrictList/' + $('#ZoneId').val(), getDistricts);
maybe you should handle your callback function with a anonymous function like this:
$.getJSON('DistrictList/' + $('#ZoneId').val(), success(data){
getDistricts(data);
})