How to Pass Model Data in JavaScript

How to pass model data in javascript

You can pass the model data into the java script file in these ways
(1). Just set the value in hidden field and access the value of hidden field in java script.
(2). And pass the value using function parameter.
(3).

        var LoginResourceKeyCollection = {
UserName_Required: '<%= Model.UserName%>',
Password_Required: '<%= Model.Password%>'

}
</script>

Pass model data to javascript function

Your call to your JS function will look like this:

<a href="#" onclick="myFunction('@Model.id')"> </a>

This will send the current id in concern to your JS function.

MVC Passing Model Data into JavaScript

I'd suggest you pass the list of numbers as a variable inside the scripts-section, instead of setting it as a data-attribute of the tag inside it. You can then use the variable in you script.

In your view:

@section scripts {
<script>
var mynumbers = "@string.Join(",", Model.numbers)";
</script>
<script id="script1" src="~/Scripts/render_sudoku.js" type="text/javascript"></script>
}

In your script:

var numbers = mynumbers.split(",");
for (var i in numbers)
{
var number = numbers[i];
// DO WHATEVER
}

Edit: You need to put the declaration of the Javascript variable inside quotes, or otherwise you will get an ESLint parsing error.

Passing asp.net mvc model into Javascript function

You need to convert Model.NextActionParam to JSON string with Json.Encode() method. Better way is put JSON inside <script> section and set some variable, then use it anywhere.

<script>
var nextActionParam = @Html.Raw(Json.Encode(Model.NextActionParam));
</script>

<input type="button" id="btnNextAction" class="btn btn-primary" value="JSFunction"
onclick="callJS(nextActionParam)" />

Passing .net core model data to external javascript?

You can get C#/Razor values as a string easily enough.

<script type="text/javascript">
var i = parseInt('@Model.i');
</script>

Or you can try with below given options.

Option 1:

var myVar = '@Model.MyVar';
var name = '@Model.Name';

Option 2:

var myVar ='@Html.Raw(Model.MyVar)';
var name = '@Html.Raw(Model.Name)';

How to pass data object with list of objects to controller

For submitting complex models, you need to ensure that the name attribute of these controls bound to the Subcategory class fields are displayed in the form of a collection index.

And trigger the addSubCategory click event in js to add Subcategory control and data.

Since you added model validation, I suggest you use ViewBag.Subcategories to save the Subcategories data that has been added to the current page to prevent data loss after clicking the validation.

And you only need to add an asp-validation-summary in your form. Since these fields belong to a model and are in a form, their error information will be counted in the asp-validation-summary div.

Here is a complete example:

   public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<Subcategory> Subcategories { get; set; }
}

public class Subcategory
{
[Required]
[DisplayName("Subcategory.Name")]
public string Name { get; set; }
}

Controller:

public IActionResult CreateCategory()
{
ViewBag.Subcategories = new List<Subcategory>() { };
return View();
}

[HttpPost]
public IActionResult CreateCategory(Category category)
{
if (!ModelState.IsValid)
{
// store Subcategories data which has been added
ViewBag.Subcategories = category.Subcategories == null ? new List<Subcategory>() { } : category.Subcategories;
return View("CreateCategory");

}
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}

View:

@model AplikacjaFryzjer_v2.Models.Category
@{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";

var SubcategoriesData = (IList<AplikacjaFryzjer_v2.Models.Subcategory>)ViewBag.Subcategories;

}

<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
@for (int i = 0; i < SubcategoriesData.Count(); i++)
{
<div class="form-group">
<label>Name@(i)</label>
<input asp-for="Subcategories[i].Name" value="@SubcategoriesData[i].Name" />
<span asp-validation-for="Subcategories[i].Name" class="text-danger"></span>
</div>
}
<button class="btn btn-primary" onclick="RemoveSubcategory(this)" id="removeSubcategory">remove</button>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
</div>

</form>
@section Scripts
{
<script>

var i = @SubcategoriesData.Count()-1;
$(document).ready(function () {
if (@SubcategoriesData.Count() <= 0) {
$("#removeSubcategory").hide();
}

$("#addSubCategory").click(function (e) {
e.preventDefault();
i++;
var name = '<label>Name' + i + '</label><input name = "Subcategories[' + i + '].Name" type="text"/>';
$("#removeSubcategory").before('<div class="form-group">' + name + '</div>');
$("#removeSubcategory").show();
});


});
function RemoveSubcategory(btn) {
event.preventDefault();
$(btn).prev("div").remove();
i--;
if (i == @SubcategoriesData.Count() -1) {
$("#removeSubcategory").hide();
}
}
</script>
}

Here is test result:

Sample Image

How to pass model object to javascript function in asp.net Core

I have solved this problem!

Solution:

Model:

public class SalesViewModel
{
public string salesdate { get; set; }
public int salesprice { get; set; }
}

Data:

public class SalesContext
{
public string ConnectionString { get; set; }

public SalesContext(string connectionString)
{
this.ConnectionString = connectionString;
}
public SalesContext()
{
}

public List<SalesViewModel> GetAllData()
{
List<SalesViewModel> list = new List<SalesViewModel>();
list.Add(new SalesViewModel() { salesdate = "1", salesprice = 3 });
list.Add(new SalesViewModel() { salesdate = "2", salesprice = 6 });
list.Add(new SalesViewModel() { salesdate = "3", salesprice = 7 });
list.Add(new SalesViewModel() { salesdate = "4", salesprice = 2 });
list.Add(new SalesViewModel() { salesdate = "5", salesprice = 1 });

return list;
}
}

Controller:

using Newtonsoft.Json;
public IActionResult Chart()
{
SalesContext sc = new SalesContext();
string json = JsonConvert.SerializeObject(sc.GetAllData());
//ViewData["chart"] = json;
ViewBag.Sales = json;
return View(sc.GetAllData());
}

View:

document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var salesdata = @Html.Raw(ViewBag.Sales);
config.data.datasets.forEach(function(dataset) {
for (var i = 0; i < salesdata.length; i++) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
dataset.data.push(salesdata[i].salesprice);
}
});

window.myLine.update();
}
});

use var salesdata = @Html.Raw(ViewBag.Sales) to get data from controller!

use salesdata[i].salesprice to push data to the dataset!

Thanks!



Related Topics



Leave a reply



Submit