In my Net Core 2.1 MVC project I have a viewmodel parameter userID, that I want to assign to a JQuery variable after the page loads. The ID is not displayed anywhere on the page.
So far, this doesn't seem to work:
View:
#{int userID = Model.ID;}
// rest of html page.
#section scripts {
<script src="~/AssigntoVariable.js"></script>
}
AssignToVariable.js
$(document).ready(function () {
$(function () {
var json = userID;
console.log(json);
// removed further code
When I run this, I receive a 'UserID not defined' error, obviously.
How can I put the userID parameter from my viewmodel directly in a JQuery script?
You can access viewmodel parameter ID as userID on client-side like:
#section scripts {
<script type="text/javascript">
var userID = #(Html.Raw(Json.Encode(Model.ID)));
// You can now access userID here
console.log(userID);
</script>
<script src="~/AssigntoVariable.js"></script>
}
and now you can also access userID in AssignToVariable.js like:
$(document).ready(function () {
var json = userID;
console.log(json);
});
Please note that you don't need to use
$(document).ready(function () {
$(function () {
both of them in AssignToVariable.js file, as $(function () { is just a shorthand for $(document).ready(function () {. Please use either one of them.
Related
I am stuck in this problem for hours if not days.
I can start the ActionResult that returns PartialView("MODEL") but I am unable to render actual View into the div inside an Index cshtml page.
Here is what I am trying:
Controller:
...
public ActionResult Calendar()
{
PopulateCalendarAsync();
return PartialView(_calendarViewModel);
}
...
Index.cshtml :
<div id="calendarDiv" ></div>
script inside Index:
<script type="text/javascript">
$(document).ready(function (e) {
$.get('#Url.Action("Calendar","Home")', {}, function (result) {
$("#calendarDiv").load("~/Home/Calendar");
});
});
When Index page loads, script calls the ActionResult Calendar() with no problems.
The problem is that div is not being updated.
my Calendar.cshtml page is aside Index page in Home folder.
What am I missing here?
The result parameter of the $.get request will contain the html output of the calendar partial view.
Assign it to the <div> via $("#calendarDiv").html(result);
Full code:
$(document).ready(function (e) {
$.get('#Url.Action("Calendar","Home")')
.then(function (result) {
$("#calendarDiv").html(result);
})
.fail(function (xhqr, status, error) {
alert(status);
alert(JSON.stringify(xhqr));
})
});
My goal is to build AJAX, which will show details of specific Building when user clicks on specific link <a...>
My Controller
public IActionResult BuildingDetail(int id)
{
return PartialView("_BuildingDetailsPartial", _buildingRepository.GetById(id));
}
My view
#foreach (var employee in Model.employees)
{
...
<a id="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId"
onclick="AssignButtonClicked(this)">#employee.Office.Name</a>
...
}
Place to show Details of Building when user clicks on link. So _BuildingDetailsPartial will render here.
<div id="BuildingDetail">
</div>
Scripts: Im stuck here. I need to load specific BuildingDetail based on passed id.
<script type="text/javascript">
$(document).ready(function () {
function AssignButtonClicked(buildingId) {
var BuildingId = $(buildingId).data('assigned-id');
}
$("#LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", { id: AssignButtonClicked() }, );
});
})
</script>
The issue is due to the logic of the click handler in jQuery. You're attempting to call a function in the onclick attribute of the element which won't be accessible as it's defined inside the document.ready scope.
Also, you're trying to set the id property of the object you send in the request to a function which has no return value.
To fix this, remove the onclick attribute from the HTML you generate, and just read the data attribute from the element directly in the jQuery event handler before you send the AJAX request. Try this:
#foreach (var employee in Model.employees)
{
<a class="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId">#employee.Office.Name</a>
}
<script type="text/javascript">
$(function () {
$(".LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", {
id: $(this).data('assigned-id')
});
});
})
</script>
Here I have ViewBag in a controller which contains text i.e ViewBag.Msg = "No Sprint".
And I am trying to use ViewBag.Msg in Jquery to display modal.
Now, the problem is that the script is script never gets executed.
Below is my jQuery.
<script>
$(document).ready(function () {
debugger;
if (#ViewBag.Msg != null)
{
$("#myModal").modal();
}
});
</script>
Any help will be highly appreciated. Thank You.
You need to use quotation marks for the view bag, as it will appear as a literal string.
If your debugger is not hitting at all, then you have another issue, post your full code. (your .cshtml file and layout)
<script>
$(document).ready(function () {
debugger;
if ('#ViewBag.Msg' != null)
{
$("#myModal").modal();
}
});
</script>
Please use the below code.
<script>
$(document).ready(function () {
debugger;
var msg='#ViewBag.Msg';
if (msg !== '')
{
$("#myModal").modal();
}
});
</script>
Hello i googled to find a solution to my problem, every link brought me to asp forms solution, or solutions that do not ask for form inputs, this problem has form inputs and i cant seem too find a link for help, what im asking for is simple: get the data from user input through models by ajax calls.
View (index.cshtml):
#model UIPractice.Models.ModelVariables
<!-- Use your own js file, etc.-->
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<div id="div1">
#Html.BeginForm(){ #Html.TextBoxFor(x => x.test1, new { style = "width:30px" })}
<button id="hello"></button>
</div>
<div id="result1"></div>
<script type="text/javascript">
//Job is to load partial view on click along with model's objects
$(document).ready(function () {
$('#hello').click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
success: function (result) {
$('#result1').html(result);
}
});
});
});
Model (ModelVariables.cs):
public class ModelVariables
{
//simple string that holds the users text input
public string test1 { get; set; }
}
Controller (HomeController.cs):
// GET: Home
public ActionResult Index()
{
ModelVariables model = new ModelVariables();
return View(model);
}
public ActionResult HelloAjax(ModelVariables model)
{
ViewBag.One = model.test1;`
return PartialView("_MPartial", model);
}
Partial View (_MPartial.cshtml):
#model UIPractice.Models.ModelVariables
#{
<div>
<!--if code runs, i get a blank answer, odd...-->
#Model.test1
#ViewBag.One
</div>
}
So go ahead and copy/paste code to run, you will notice that you get nothing when you click the button, with user text input, odd...
I see a few problems.
Your code which use the Html.BeginForm is incorrect. It should be
#using(Html.BeginForm())
{
#Html.TextBoxFor(x => x.test1, new { style = "width:30px" })
<button id="hello">Send</button>
}
<div id="result1"></div>
This will generate the correct form tag.
Now for the javascript part, you need to prevent the default form submit behavior since you are doing an ajax call. You can use the jQuery preventDefault method for that.
$(document).ready(function () {
$('#hello').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '#Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
success: function (result) {
$('#result1').html(result);
}
,error: function (a, b, c) {
alert("Error in server method-"+c);
}
});
});
});
Also, you might consider adding your page level jquery event handlers inside the scripts section (Assuming you have a section called "scripts" which is being invoked in the layout with a "RenderSection" call after jQyery is loaded.
So in your layout
<script src="~/PathToJQueryOrAnyOtherLibraryWhichThePageLevelScriptUsesHere"></script>
#RenderSection("scripts", required: false)
and in your indidual views,
#section scripts
{
<script>
//console.log("This will be executed only after jQuery is loaded
$(function(){
//your code goes here
});
</script>
}
I want to retrieve property value in jquery function and want to set it in variable. I am trying with below code but its not working.
.cs file
private string _Heading;
public string Heading { get { return _Heading; } set { _Heading = value; } }
.aspx
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowSimple").click(function (e) {
ShowDialog(false);
e.preventDefault();
var someProp = "<%= this._Heading; %>";
alert(someProp);
});
</script>
What should i do to retrieve property value?? Anyone have solution than please help me in this.
Firstly, if the variable is private you will not be able to access it in your JavaScript so you should use the public Heading property instead.
Secondly, you have a semi colon in your JavaScript which needs to be removed so change this line
var someProp = "<%= this._Heading; %>";
To this
var someProp = "<%=this.Heading%>";