I'm using ASP.NET Controller accessing account data to another database. I'm doing a login where it gets an ID and checks if it's a Mentor or Student.
With this information we want it to be used in a .js file we have thats makes a get request to our server. We want to send an ID here and later other informations.
We have this controller:
public IActionResult Calendar(LoginViewModel loginViewModel)
{
Student student = null;
Mentor mentor = null;
if (loginViewModel.UserType == 0)
{
student = db.GetStudentObject(loginViewModel.Id);
}
else if (loginViewModel.UserType == 1)
{
mentor = db.GetMentorObject(loginViewModel.Id);
}
if (student != null)
{
return View(student.Id);
}if(mentor != null)
{
return View(mentor.Id);
}
return View("Index");
}
When our view is initialized we want to send an ajax request where we use the Id we sent to the view
eventSources: [
{
url: '/api/Bookings?id=' + id, //we need to access the Id here
color: 'blue',
textColor: 'white'
}
],
How can we retrieve the Id from the controller we are sending to the view? I know this can be solved by making a static class however is there a better options?
//Accessing the Id on JS file:
'/api/Bookings?id=' + $('#Id').val();
#*
if the view is binding to a complex model, you must return View(model), instead of View(model.Id) on controller.
assuming that is a complex model, you have in your view (cshtml):
*#
#model Xpto.Models.MyViewModel
#Html.HiddenFor(i => i.ID) //to access the property on JS file.
Related
I have this URL
var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;
and in my Test controller I do this to get query string value
tM_PMO.Type = Request.QueryString["CmpT"];
But always give me null values.
There is a difference between the GET and POST types.
Query string can be read with the URL of the GET request. However, you cannot read the Query string value in the URL when you make a POST request. For this you need to submit it to the server.
Below I give you a few examples of usage.
GET Request
You can read Query string with URL as below
public ActionResult Test(string CmpT)
{
if (!string.IsNullOrWhiteSpace(CmpT))
{
//your codes...
}else
{ }
return View();
}
POST Request
If you are making a POST request and trying to read from the URL, it will return null. In order to read it, you need to send this value to the server as follows.
1st way : In your Html.BeginForm in your View Below, submit Query string as below and read this value as Action parameter
View Page
#using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
2nd way : Create a hidden form element as part of the form between the Html.BeginForm tags in your view page and give its value as a query string. Then call it in Action method like below.
View Page
#using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
#Html.Hidden("returnUrl", Request.QueryString["CmpT"])
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
or for multiple form items (You can also access other form elements this way)
public ActionResult Test(FormCollection fc)
{
string _returnUrl = fc["returnUrl"];
if (!string.IsNullOrWhiteSpace(_returnUrl))
{
//your codes...
}else
{ }
return View();
}
I hope you are looking for below code sample where we just fetch the value in url which we says query string:
Request.QueryString["querystringparamname"].ToString();
You can assign this in any Var and use accordingly.
I am sort of lost on the coding part of this problem. I have a MVC application, and I am trying to populate a queries Where clause as the selected value from my drop down list. Also, I am populating the drop down list from a query in the database. For example:
SELECT db.ID FROM Database db where ID = 1232
Instead of that, I want to do something like this...
SELECT db.ID FROM Database db where ID = "SelectedValue from Dropdownlist"
Model Class:
public string ID {get; set;}
public string Summary{get; set;}
public int Estimate {get; set;}
public List<Hello> getIDs()
{
var que = (from wre in db.Table
select new Hello{
ID = wre.ID
}).toList();
}
Controller class:
public ActionResult Index(string? IDParam)
{
var model = test.getStuff();
var que = (from wre in db.View
where wre.ID == IDParam //Operator '==' cannot be applied to operands of type 'string' and 'string?'
select new Hello
{
ID = wre.ID
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
if (IDParam!= null & IDParam.HasValue)
{
model = model.Where(x => x.ID == IDParam); //Operator '==' cannot be applied to operands of type 'string' and 'string?'
}
return View(model);
}
View Class:
#Html.DropDownList("ID", ViewBag.Releases as SelectList, "ID", new {#id="rel" })
<table>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Estimate)</th>
</table>
<script>
$("#rel").change(function () {
var selectedId = this.val();
location.href = '#Url.Action("Index", "SampleController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
</script>
This works perfectly fine, but now, I am lost on the coding aspect of it. I can see the alert every time I change the ID from the drop down list. However, there is no change in the data being displayed (I know I am missing a lot). If anyone can help me out here, that would be great, thank you!
1) Try adding where clause in Linq
where wre.ID == IDParam
2) Change que to instance of your class and get firstOrDefault instead of List
3) Try passing instance of your class as a model in view
return View(test);
1- You need to get changed Id as below :
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
});
2- If you want to reload your page then you need to set a parametre to your [HttpGet] Method :
public ActionResult Index(int? selectedId) // selectedId
{
var que = (from wre in db.View
select new Hello
{
ID = IDParam
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
ViewBag.Releases = new SelectList(test.getIDs(), "", "ID");
var model = test.getStuff();
if(selectedId!=null && selectedId.HasValue)
{
// do some stuff with your selectedId
// if working method is test.getStuff(), then maybe you can use like code below:
model = model.Where(x=> x.Id==selectedId);
}
return View(model);
}
and in your View:
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
location.href = '#Url.Action("Index", "YourController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
3- If you dont want to reload page then you need to use Ajaxrequest, You must create a new method for get data by selectedId,
// Your view.
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
$.ajax({
method: "POST",
url: "'#Url.Action("GetDataBySelectedId","YourController")'",
data: { selectedId: selectedId }
})
.done(function( data) {
// Delete your table, and fill table with your data with jquery.
});
});
// your Controller:
[HttpPost]
public JsonResult GetDataBySelectedId(int? selectedId)
{
// Do some stuff for get your data.
var data = yourData.Where(x=> x.Id = selectedId.Value);
return Json(data);
}
I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).
I am developping an ASP MVC 5 application and I am heading up a problem with the showing of a Toast's Notifaction.
The toast notifaction appears after updating the informations of a user in order to confirm the success of operation.
Unfortunately it disappears quickly (in 2 seconds) after the loading of the next page. I think this is due to the using of server side code (C# in this case), where the entire page reloads, including the javascript files. This is why the toastr disappears too.
Is there any way to keep it a lil longer ?
I tried to o pass the necessary information to the next page, so that page two would know to display the toastr instead of page1 but it didn't work.
This is the code's snippet :
View :
#using (Html.BeginForm("Edit", "Client", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<input type="submit" value="Save" class="btn btn-default" onclick="Update()">
}
<script src="/template/web/js/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/toastr.js"></script>
<script>
function Update() {
toastr.success("Your infos are updated with succes !");
}
</script>
Controller :
[HttpPost]
public ActionResult Edit(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.UpdateDetails(cmodel))
{
ViewBag.Message = "Client Details Edited Successfully";
}
return RedirectToAction("Profil");
}
catch
{
return View();
}
}
Profil :
public ActionResult Profil()
{
ClientManagement dbhandle = new ClientManagement();
ViewBag.Message = TempData["Message"];
return View(dbhandle.GetClientsInfo());
}
In View Profil (buttom of page) :
<link href="~/Content/toastr.min.css" rel="stylesheet" />
script src="~/scripts/toastr.js"></script>
<script src="~/scripts/toastr.min.js"></script>
#if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("#ViewBag.Message");</script>
}
If you want to pass one-time message from an action method to another action method, you will need to use TempData.
[HttpPost]
public ActionResult Edit(int id, Client cmodel)
{
try
{
ClientManagement cdb = new ClientManagement();
if (cdb.UpdateDetails(cmodel))
{
TempData["Message"] = "Client Details Edited Successfully";
}
return RedirectToAction("Profil");
}
catch
{
return View(cmodel);
}
}
You then retrieve it at the next page either inside action method or view. Please note that it would be cleared out at the end of the request after you read it.
Profil.cshtml
#if (TempData["Message"] != null)
{
<script type="text/javascript">toastr.success("#TempData["Message"]");</script>
}
Update
Above code works. If you use default ASP.NET MVC Layout, please make sure you place the script inside Scripts section, so that it renders after jQuery.
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
#if (TempData["Message"] != null)
{
<script type="text/javascript">toastr.success("#TempData["Message"]");</script>
}
}
FYI: If you use toastr in other places, you might want to consider bundle and minfy them with other scripts and styles.
If you don't need to redirect to "Profil", then I agree you could use Ajax and on the success callback you could show your toastr. If you need to redirect then you can set the ViewBag.Message as you do and then do something like
#if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("#ViewBag.Message");</script>
}
I have a script that renders a partial view after its data is loaded, but I want at least one other partial view to load using the same data. It's a long-running query (30sec - 1min), so I don't want to load it for each partial view. Or am I going down the wrong path? It should be noted I'm still pretty new to ASP.Net and very new to Javascript/Jquery, so I'm not totally aware of best practices, so if you spot something that's "against convention", please let me know that, too.
EDIT: It dawned on me I should note what I'm trying to eventually get to. In my current non-ASP app (C#/XAML), it loads the data (with an equivalent of LoadMonitorData method, below) when the app loads, then refreshes every 15 minutes. Or the refresh can be triggered by a Refresh button.
Here's what I've got so far...any help or guidance would be greatly appreciated.
Index.cshtml
#{
ViewBag.Title = "MMCView";
}
#section scripts {
<script type="text/javascript">
$(document).on('click', '[name^=project]', function () {
if ($(this).hasClass('selected')) {
$('.mig-project').removeClass('selected').removeClass('low-opacity').addClass('full-opacity');
$('#data-area').removeClass('show-data-view');
}
else {
$(this).addClass("selected").addClass('full-opacity').removeClass('low-opacity');
$('.mig-project').not(this).removeClass("full-opacity").removeClass('selected').addClass("low-opacity");
$('#data-area').load($(this).data("url"));
$('#data-area').addClass('show-data-view');
}
})
</script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#list-container").each(function(index, item) {
var url = $(item).data("url");
if (url && url.length > 0) {
$(item).load(url);
}
})
})
</script>
}
<div class="project-list slow-load" id="list-container" data-url="/mmc/projectpanes">
<img src="loading.gif" />
</div>
<div class="hide-data-view slow-load" id="data-area" data-url="/mmc/projectdata"></div>
MMCController.cs
using MMC_ASP.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace MMC_ASP.Controllers
{
public class MMCController : AsyncController
{
MonitorData downloadedInfo = new MonitorData();
//GET: MMC
public ActionResult Index()
{
return View();
}
public ActionResult ProjectPanes()
{
downloadedInfo = LoadMonitorData();
return PartialView("_ProjectPanes", downloadedInfo.MainPanel.OrderBy(o => o.Client).ToList());
}
public ActionResult ProjectData(string server)
{
return PartialView("_ProjectData", downloadedInfo.Information.Where(x => x.ServerName == server).ToList());
}
public ActionResult MainWindowMonitor()
{
return PartialView("_MainWindowMonitor", downloadedInfo.MonitorText);
}
public MonitorData LoadMonitorData()
{
MonitorData deserializedData = null;
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.Unicode;
string location = "http://MYWEBAPI-RETURNS-JSON";
string data = wc.DownloadString(new System.Uri(location));
var deserializer = new JavaScriptSerializer();
deserializedData = deserializer.Deserialize<MonitorData>(data);
}
return deserializedData;
}
}
}
In this situation, the Cache object might be useful to you. You can store your data in the Cache, set it to expire after a reasonable amount of time, write a helper function to re-pull the data on the fly if the cached data has expired, and have your partial views pull their data from the helper function. This way, the new data will only be pulled as needed, regardless how many views are using it, and as a bonus you have easy control over how often to re-execute that expensive query.
Note that this works well in your situation because your data is global in nature. If you were passing user-specific parameters into your query, then Cache wouldn't be a good fit.
using System.Web.Caching;
private MonitorData getCachedData()
{
var cache = this.HttpContext.Cache;
if (cache["MonitorData"] == null)
cache.Add("MonitorData", LoadMonitorData(), null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); // 15 minute cache expiration, as example
return (MonitorData)cache["MonitorData"];
}
public ActionResult ProjectPanes()
{
downloadedInfo = getCachedData();
return PartialView("_ProjectPanes", downloadedInfo.MainPanel.OrderBy(o => o.Client).ToList());
}
public ActionResult ProjectData(string server)
{
downloadedInfo = getCachedData();
return PartialView("_ProjectData", downloadedInfo.Information.Where(x => x.ServerName == server).ToList());
}
public ActionResult MainWindowMonitor()
{
downloadedInfo = getCachedData();
return PartialView("_MainWindowMonitor", downloadedInfo.MonitorText);
}
The solution that Joe_Irby proposed works great! However, while communicating with him I found another approach that works as well. I figured I'd include it here so anyone else looking for a solution can decide which one will be best for their situation.
https://code.msdn.microsoft.com/Caching-In-Web-API-cb40be30