how to fetch workerID in my kendoDropdown list - asp.net-mvc-3

i have a kendodropdown list with the workername and details... how can i fetch the ID of the selected worker so i can able to save... everytime i save it returns a null value in ID.. thanks for those who can help
Heres my code:
<input id="titles" class:"validate[required] inputLong" style="width: 400px;" />
$(document).ready(function () {
var clientCusPosId = $("#clientCusPosId").val();
$("#titles").kendoDropDownList({
dataTextField: "workerName",
dataValueField: "workerID",
autoBind: false,
// define custom template
template:
'<h5>${ data.workerName }</h5>' +
'<p>${ data.workerID }</p>' +
'<p>${ data.AvailableDay_LookID }</p>' +
'<p>${ data.StartTime } - ${ data.EndTime }</p>',
optionLabel: "Assign worker",
dataSource: {
transport: {
read: {
url: '/Client/LoadWorkerDropdownList?clientCusPosId=' + clientCusPosId,
dataType: "json",
type: "POST"
}
}
}
});
var dropdownlist = $("#titles").data("kendoDropDownList");
dropdownlist.list.width(250);
});
My Controller:
[Authorize]
[HttpPost]
public ActionResult ClientWorkerPositionSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientWorkerPosId = formCollection["clientWorkerPosId"];
String clientID = formCollection["clientId"];
String clientCusId = formCollection["clientCusPosId"];
String workerID = formCollection["titles"];
Client_Worker_Position clientCusPos = new Client_Worker_Position();
try
{
if (String.IsNullOrWhiteSpace(clientWorkerPosId) || clientWorkerPosId == "0")
{
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateCreated = DateTime.UtcNow;
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.CreatedBy = User.Identity.Name;
clientCusPos.ModifiedBy = User.Identity.Name;
db.Client_Worker_Position.Add(clientCusPos);
}
else
{
int id = Convert.ToInt32(clientWorkerPosId);
clientCusPos = (from a in db.Client_Worker_Position
where a.ID == id
select a).SingleOrDefault();
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
return RedirectToAction("ClientCustomerDetails", new { });
}

It could be as simple as using $("#titles).val() to get your WorkerID since it has already been configured.
Create a hidden input field hidden id="workerID" then before your post or in a drop down change event set it to $("#workerID").val($("#titles).val()). This should come across in your controller collections.

Related

Getting Status 400 error while posting data on server in Razor page and AJAX

I am developing a website related to medical treatment, in which we ask different type of questions from patient actually, my task is, to enter their Email so I can check if he is already registered or not logged in then I redirect the user to the login page else I can register the user and assign a random password to the user and send him a mail on that Email,
so logged in user and if a user is not logged in these flows are working fine but when I'm when I register the user then and come to the next question I'm getting an error of status 400
Code for checking for user:
public async Task<IActionResult> OnGetCheckUserAsync(string Email)
{
if (User.Identity.IsAuthenticated)
{
var UserCred = _userManagmentServices.GetProfileAsync(Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
var user = await _userManager.FindByEmailAsync(Email);
if (user == null)
{
string randomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!##$%^&*";
Random random = new Random();
char[] myPassword = new char[6];
for (int i = 0; i < 6; i++)
{
myPassword[i] = randomString[(int)(35 * random.NextDouble())];
}
var randomPassword = string.Concat(myPassword);
var UserModel = new UserModel()
{
Email = Email,
FirstName = "Mr",
LastName = "Patient",
Password = randomPassword,
PhoneNo = "03000000000",
};
var response = await _userManagmentServices.CreateAsync(UserModel);
if (response.IsSuccessful)
{
var Body = $"Dear {UserModel.FirstName + UserModel.LastName} Your password is auto generated successfull and your password is {UserModel.Password}";
await _mailServices.SendEmailNotificationAsync(UserModel.Email, "Auto Generated Password", Body);
}
if (!response.IsSuccessful)
{
foreach (var Error in response.Errors)
{
ModelState.AddModelError("", Error.ToString());
}
return new JsonResult("Error while creating your account");
}
var UserCred = _userManagmentServices.GetProfileAsync(UserModel.Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
application = new FEApplication();
application.Status = Status.Incomplete;
application.UserEmail = Email;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
var _signinUrl = "../Auth/Signin";
return new JsonResult(_signinUrl);
}
}
}
public async Task<IActionResult> OnPostSubmitAsync(FEApplication? application)
{
if (application.FlowId != null)
{
application.ApplicationType = "Premature Ejaculation";
if (application.DoctorToKnow == "No" || application.ExplainDoctorToKnow != null)
{
application.Status = Status.PaymentDue;
}
else
{
application.Status = Status.Incomplete;
}
await _applicationManagementService.UpdatePEAsync(application.FlowId, application);
}
else
{
if (User.Identity.IsAuthenticated)
{
application.PatientUserName = ProfileModel.DisplayName;
application.ApplicationType = "Premature Ejaculation";
application.Status = Status.Incomplete;
application.UserEmail = User?.Identity?.Name;
ProfileModel = _userManagmentServices.GetProfileAsync(application.UserEmail).Result;
}
else
{
application.PatientUserName = ProfileModel.DisplayName ?? string.Empty;
application.UserEmail = application.UserEmail;
}
application.Status = Status.Incomplete;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
//_application = _applicationManagementService.GetOneById(FlowId);
}
return new JsonResult(application.FlowId);
}
function CheckUserEmail() {
$("#modalspinner").show();
var email = document.getElementById("Email").value;
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
url: "./Start?handler=CheckUser",
type: "GET",
dataType: "json",
data: {
Email: email
},
success: function (response) {
console.log("Success block");
if (response) {
$("#modalspinner").hide();
console.log("response " + response)
if (response == "../Auth/Signin") {
window.location.href = response;
}
else {
if (response.id) {
console.log("if block =" + JSON.stringify(response));
var firstName = JSON.stringify(response.displayName) ?? "";
var lastName = JSON.stringify(response.displayName) ?? "";
var email = JSON.stringify(response.email) ?? "";
var phoneNo = JSON.stringify(response.phone);
var address = JSON.stringify(response.address) ?? "";
var city = JSON.stringify(response.city);
var postalCode = JSON.stringify(response.postalCode) ?? "";
$("#FirstName").val(firstName.replace(/\"/g, ""));
$("#LastName").val(lastName.replace(/\"/g, ""));
$("#Email").val(email.replace(/\"/g, ""));
$("#PhoneNoTextbox").val(phoneNo.replace(/\"/g, ""));
$("#CustomerShippingAddress").val(address.replace(/\"/g, ""));
$("#CustomerCity").val(city.replace(/\"/g, ""));
$("#CustomerPostalCode").val(postalCode.replace(/\"/g, ""));
console.log("response data :" + firstName, lastName, email, phoneNo, address, city, postalCode);
}
else {
$("#modalspinner").hide();
console.log("Error while creating new user" + JSON.stringify(response));
}
}
}
},
error: function (response) {
console.log("Error block =" + JSON.stringify(response));
$("#modalspinner").hide();
$('#EmailMessage').show();
setTimeout(function () { $('#EmailMessage').hide(); }, 5000);
$("#modalspinner").hide();
}
});
}
function SubmitForm() {
/*var flowId = document.getElementById("FlowId").value;*/
var data = $("#ApplicationData").serialize();
console.log("data :" + data);
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
type: "POST",
url: "./Start?handler=Submit",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data,
success: function (response) {
var res = JSON.stringify(response);
console.log("Application data saved!");
$("#FlowId").val(res.replace(/\"/g, ""));
}
})
}
Please check below with your code:
In the cshtml, add
#Html.AntiForgeryToken()
The Ajax request should send the anti-forgery token in request header to the server.
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
In startup, since the script sends the token in a header called XSRF-TOKEN, configure the antiforgery service to look for the XSRF-TOKEN header:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Error passing multiple input files, Design Automation Revit dot net core

I had asked my last question regarding this. I have one rfa file and a bigger JSon file as input. When I debug, it looks perfectly passing all values until last line:
WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
Looks like workItemSpec has some problem. Please have a look at these code fractions and please let me know what is wrong here.
code fraction from ForgeDesignAutomation.js as below:
{
var inputFileField = document.getElementById('inputFile');
if (inputFileField.files.length === 0) { alert('Please select an input file'); return; }
if ($('#activity').val() === null) { alert('Please select an activity'); return };
var file = inputFileField.files[0];
var inputFileField2 = document.getElementById('inputJsonFile');
if (inputFileField2.files.length === 0) { alert('Please select an input file'); return; }
var file2 = inputFileField2.files[0];
let activityId = $('#activity').val();
if (activityId == null)
{
alert('Please select an activity'); return
};
if (activityId.toLowerCase() === "_da4ractivity+dev")
{
startConnection(function () {
var formData = new FormData();
formData.append('inputFile', file);
formData.append('inputJsonFile', file2);
formData.append('data', JSON.stringify({
activityName: $('#activity').val(),
browerConnectionId: connectionId
}));
writeLog('Uploading input file...');
$.ajax({
url: 'api/forge/designautomation/workitems',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (res)
{
writeLog('Workitem started: ' + res.workItemId);
}
});
});
}
}```
code fraction from "CreateActivity" in DesignAutomationController.cs
``` Parameters = new Dictionary<string, Parameter>()
{
{ "inputFile", new Parameter() { Description = "input file", LocalName = "$(inputFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "inputJsonFile", new Parameter() { Description = "input Json file", LocalName = "$(inputJsonFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "outputFile", new Parameter() { Description = "output file", LocalName = "outputFile." + engineAttributes.extension, Ondemand = false, Required = true, Verb = Verb.Put, Zip = false } }
}```
code fraction from "StartWorkitem" in DesignAutomationController.cs
``` [HttpPost]
[Route("api/forge/designautomation/workitems")]
public async Task<IActionResult> StartWorkitem([FromForm]StartWorkitemInput input)
{
// basic input validation
JObject workItemData = JObject.Parse(input.data);
string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value<string>());
string browerConnectionId = workItemData["browerConnectionId"].Value<string>();
// save the file on the server
var fileSavePath0 = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName));
using (var stream0 = new FileStream(fileSavePath0, FileMode.Create)) await input.inputFile.CopyToAsync(stream0);
var fileSavePath1 = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputJsonFile.FileName));
using (var stream1 = new FileStream(fileSavePath1, FileMode.Create)) await input.inputJsonFile.CopyToAsync(stream1);
//---------------------------------------------------------------------------------------------------------------------
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// upload file to OSS Bucket
// 1. ensure bucket existis
string bucketKey = NickName.ToLower() + "-designautomation";
BucketsApi buckets = new BucketsApi();
buckets.Configuration.AccessToken = oauth.access_token;
try
{
PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
await buckets.CreateBucketAsync(bucketPayload, "US");
}
catch { };
// in case bucket already exists
// 2. upload inputFile
string inputFileNameOSS0 = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
string inputFileNameOSS1 = string.Format("{0}_inputJson_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputJsonFile.FileName)); // avoid overriding
//string inputFileNameOSS = Path.GetFileName(input.inputFile.FileName); // avoid overriding
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
using (StreamReader streamReader = new StreamReader(fileSavePath0))
await objects.UploadObjectAsync(bucketKey, inputFileNameOSS0, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
System.IO.File.Delete(fileSavePath0);// delete server copy
// prepare workitem arguments
// 1. input file
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS0),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
using (StreamReader streamReader1 = new StreamReader(fileSavePath1))
await objects.UploadObjectAsync(bucketKey, inputFileNameOSS1, (int)streamReader1.BaseStream.Length, streamReader1.BaseStream, "application/octet-stream");
System.IO.File.Delete(fileSavePath1);// delete server copy
// 1. input Json file
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS1),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 3. output file
string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "inputFile", inputFileArgument },
{ "inputJsonFile", inputJsonArgument },
{ "outputFile", outputFileArgument },
{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec);
return Ok(new { WorkItemId = workItemStatus.Id });
}```
```/// <summary>
/// Input for StartWorkitem
/// </summary>
public class StartWorkitemInput[![enter image description here][1]][1]
{
public IFormFile inputFile { get; set; }
public IFormFile inputJsonFile { get; set; }
public string data { get; set; }
} ```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/GktUC.png
I noticed your activity defines the "localName" of "inputFile"/"inputJsonFile" to be "$(inputFile)"/"$(inputJsonFile)"
Parameters = new Dictionary<string, Parameter>()
{
{ "inputFile", new Parameter() { Description = "input file", LocalName = "$(inputFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } },
{ "inputJsonFile", new Parameter() { Description = "input Json file", LocalName = "$(inputJsonFile)", Ondemand = false, Required = true, Verb = Verb.Get, Zip = false } }
}
This could cause some issue when resolving the naming of inputs during the job process. I would suggest you provide a concrete filename as WorkItem argument's localname and try again. For example:
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS1),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
},
// Note: if your appbunldes(addin) uses this json, this is the name your addin should know
LocalName = "inputJson.json"
};

MVC Ajax function call twice

I have a problem with an ajax function. I want to send param to method on controller and this ajax function call method twice.
ajax:
$(document).ready(function () {
$(document).on('click', '.exp', function (e) {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
})
$(".exp").click(function() {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
?
<th>
Start date: #Html.TextBox("start_date", null, new { #class = "dateClass start", id = "StartDate" })
End date: #Html.TextBox("end_date", null, new { #class = "dateClass end", id = "EndDate", #data_toggle = "popover", #data_content = "End date should be greater than Start date. ", #title = "Attention" })
#Html.ActionLink("Export Report", "Report_CLeav", "Reports", new { #class = "IndexButton exp", #style = "text-decoration: none;color:white" })
</th>
"Controller"
public class ReportsController : Controller
{
// GET: Export
public ActionResult Index()
{
return View();
}
public void Report_CLeav(DateTime ?start_date, DateTime ? end_date)
{
string path = HttpContext.Server.MapPath("~/App_Data/reports/Report_LeavingCompanyHCT.xlsx");
Models.Report.Report_CompLeav reportcompleav = new Models.Report.Report_CompLeav();
var fileinfo = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(fileinfo))
{
var currentWorksheet = package.Workbook.Worksheets["HC"];
using (var excelToExport = new ExcelPackage())
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
var workBook = excelToExport.Workbook.Worksheets["HC"];
try
{
workBook = reportcompleav.exportAllEmployeeDataRRecords(workBook,start_date,end_date);
}
catch (Exception e)
{
ViewBag.IsError = true;
}
excelToExport.Save();
Stream stream = excelToExport.Stream;
var memoryStream = stream as MemoryStream;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileinfo.Name);
Response.BinaryWrite(memoryStream.ToArray());
}
}
}
}
}

returning different javascript object from controller

my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}

sending multiple parameters asp.net mvc jquery ajax

I get server error:status of 500 when I try to send 2 parameters to my action in a controller with jquery ajax, dont know why?
this is the jquery code:
$(".genreLinks").click(function () {
var genreId = $(this).attr("name");
var songId = $("#hiddenRank").val();
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyTopTenFavToPlaylist/",
type: "POST",
data: { id: songId, genre: genreId },
success: function (data) {
if (data.status === 1) {
HideAjaxLoader(), ShowMsg("Song Added Successfully")
}
else if (data.status === 4) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data.status === 3) {
HideAjaxLoader(), ShowMsg("Cannot add the song. The song was most likely modified or Deleted, we advise you to refresh the page");
}
else if (data.status === 2) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
controller's action code that accepts two parameters from my request:
[HttpPost]
public ActionResult AddPointAndCopyTopTenFavToPlaylist(int id, int genre)
{
var song = repository.GetTopTenFav(id);
if (song != null)
{
if (!(song.UserName.ToLower() == User.Identity.Name.ToLower()))
{
foreach (var item in song.Points)
{
if (User.Identity.Name.ToLower() == item.UsernameGavePoint.ToLower())
{
return Json(new { status = 2 }, JsonRequestBehavior.AllowGet);
}
}
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = song.Title;
newSong.YoutubeLink = song.YoutubeLink;
newSong.GenreId = genre;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = song.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.TopTenFavId = id;
repository.AddPoint(point);
repository.Save();
return Json(new { status = 1 }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { status = 4 }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { status = 3 }, JsonRequestBehavior.AllowGet);
}
}
I have also registered my new route:
routes.MapRoute(
"AddPoint", // Route name
"{controller}/{action}/{songId},{genreId}", // URL with parameters
new { controller = "Home", action = "", songId = UrlParameter.Optional, genreId = UrlParameter.Optional } // Parameter defaults
);

Resources