Unable to get value from model in javascript - javascript

I am new in MVC environment and I just started upgrading a website.
Problem
Object reference not set to an instance of an object.
Explanation
I have javascript function for a button in the view and I am trying to get a property value CurrentPageNo from the associated model as shown below.
$('#pPrevious').on('click', function (event) {
event.preventDefault();
this.blur();
if (ShowBusy()) {
getPageIndexChanging(#Model.CurrentPageNo-1);
}
});
I am referring to the model as below:
#code
ViewBag.Title = "Home"
End Code
#ModelType HomeModel
#Using (Html.BeginForm("Index", "Home", FormMethod.Post, New With {.id = "indexForm", .name = "indexForm"}))
Try
#Html.AntiForgeryToken()
etc...
When I put a breakpoint in the model it doesn't work.
What Am I doing wrong in this situation ?

It is difficult to Get c# model data in your javascript code.
Simply you can add the value in a text box that is hidden and get value with getElementById in your javascript code.

Related

Change View in mvc based on dropdownlist item selection

I have a dropdownlist on a View as:
<p>
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text = "Show Active", Value = "0" },
new SelectListItem{ Text = "Show Deleted", Value = "1" }},
new
{
onchange = #"
var form = document.forms[0];
form.action='deletedDistricts';
form.submit();"
})
and I am referring it to controller action as:
[HttpPost]
[ActionName("deletedDistricts")]
public ActionResult deletedDistricts()
{
var d = hc.deletedDistricts.ToList();
return View(d);
}
but JavaScript is giving a runtime error as:
0x800a138f - JavaScript runtime error: Unable to set property 'action' of undefined or null reference
I am not very good at JavaScript. Any idea why this code is throwing Null reference?
Well I can't see that you would have a form associated with a dropdown, make sure that it's wrapped with:
#using(Html.BeginForm("deletedDistricts", controllerName, FormMethod.Post)) {
// drowpdown here
}
And remove form.action='deletedDistricts';
conrollerName should be name of your controller as a string.
Let's read the error you are getting once again:
0x800a138f - JavaScript runtime error: Unable to set property 'action'
of undefined or null reference
OK, now let's read your code once again to see where you are attempting to set an action property. Looks like that's happening right over here:
form.action='deletedDistricts';
Alright, so it seems like the form instance is undefined at this stage. So the obvious next step you would like to look at is where is this form instance coming from. And you wouldn't be surprised to find this line of code of yours:
var form = document.forms[0];
Cool, you seem to be attempting to retrieve the first <form> element in your DOM. But do you have such element? Did you ever use the Html.BeginForm helper to render an HTML form? Answering those simple questions would definitely put you on the right track. Don't hesitate to inspect the markup you are generating in the browser. I am sure this would help you figure out the missing bits.

Insert Javascript variable into Html.Partial ViewDataDictionary ASP.NET MVC

I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/

Pass Spring model vars from JSP template to javascript

Within a <script> tag in a jsp file I have some code that looks like this:
var chart = new myChart({'id': ${user.id}, 'type': ${user.type}, 'name': {user.name});
Where user is a Spring model attribute set on the server side. My problem is that passing each different field of user feels clunky. It would be nice if I could do something like this:
var chart = new myChart('user': "${user}");
However when done this way the value of ${user} will be an object string that looks like this:
User{id=1, type='admin', name='foo'}
I know that I could just parse this string into an object in my external js, but it feels like there should be a cleaner way to do this. Thanks for the help.
EDIT: Going off of Cameron's answer below I could add this to my server-side controller code:
model.put("user", user);
String userJSON = MyJSONSerializer.serialize(user);
model.put("userJSON", userJSON);
Then in my JSP I could do:
var chart = new myChart({'user': JSON.parse('${userJSON}')});
This does solve my problem of having a messy options object, but it brings up the issue of using two model attributes for the same exact data. It would be ideal if I could use one model attribute for the user object, and then could somehow encode it to JSON on the fly.
You can convert the Object to JSON using a library like Jackson:
public static String objectAsJSON(Object obj) {
try
{
// This could be optimized by making a static ObjectMapper
return new ObjectMapper().writeValueAsString(obj);
}
catch (IOException e)
{
// Log exception and re-throw or return null
return null;
}
}
You could either call this method before putting the objectin your model and reference the String in your JSP like this:
var chart = ${jsonChart};
Or you could write a custom taglib and call objectAsJSON() from there. Then the actual myChart object could go in your model once. Your JSP might look like:
var chart = <chartlib:toJson obj="${chart}" />;

How to get spring mvc controller model key value inside javascript?

I am using a spring mvc controller. Inside controller i am putting some value lets say string inside model. Now i would like to retrive that value or lets just say print that value inside a javascript. How do i do it?
Here is my controller class. I am adding "movie" as key. Now i want to display that name of the movie inside java script (Not inside JSP. However Inside JavaScript)
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.GET)
public String getMovie(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
here is my JSP
<html>
<head>
//I want to print movie name inside java script not inside jSP body tag.
<script type="text/javascript">
var movie_name = ${movie};
alert("movies name"+ movie_name);
</script>
</head>
<body>
<h3>Movie Name : ${movie}</h3>//When i print here its working fine.
</body>
</html>
Use this:
var movie_name = "${movie}";
instead of:
var movie_name = ${movie};
When using ${movie}, the value gets placed on the page without quotes. Since I'm guessing it's a string, Javascript requires strings be surrounded by quotes.
If you checked your browser's console, you probably would've seen an error like Unexpected identifier or ___ is not defined.
Try this...
If you had added the object into the model as:
model.addAttribute("someObject", new Login("uname","pass"))
Then you get the properties of the model object as
var user_name = ${someObject.uname}; // This is assuming that the Login class has getter as getUname();
var user_pass = ${someObject.pass};
<html>
jsp code ...
<script>
some js code ..
..
var formProperty = <c:out value="${fromBean.property}" />
</script>
..
</html>
This worked for me where formBean is the name of form backing object and property is filed of the form class

how to call javascript function in html.actionlink in asp.net mvc?

How can one call a javascript function in html.actionlink in asp.net mvc?
I want to call one method, which is in JavaScript, but how I call it within html.actionlink in the same page?
you need to use the htmlAttributes anonymous object, like this:
<%= Html.ActionLink("linky", "action", "controller", new { onclick = "someFunction();"}) %>
you could also give it an id an attach to it with jquery/whatever, like this:
<%= Html.ActionLink("linky", "action", "controller", new { id = "myLink" }) %>
$('#myLink').click(function() { /* bla */ });
For calling javascript in your action link you simply need to write actionlink like this:
#Html.ActionLink("Delete", "Your-Action", new { id = item.id },
new { onclick="return confirm('Are you sure?');"})
Don't get confused between route values and the html attributes.
<a onclick="MyFunc()">blabla..</a>
There is nothing more in #Html.ActionLink that you could utilize in this case.
And razor is evel by itself, drop it from where you can.
#Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})
This is a bit of an old post, but there is actually a way to do an onclick operator that calls a function instead of going anywhere in ASP.NET
helper.ActionLink("Choose", null, null, null,
new {#onclick = "Locations.Choose(" + location.Id + ")", #href="#"})
If you specify empty quotes or the like in the controller/action, it'll likely add a link to what you listed. You can do that, and do a return false in the onclick. You can read more about that at:
What's the effect of adding 'return false' to a click event listener?
If you're doing this onclick in an cshtml file, it'd be a bit cleaner to just specify the link yourself (a href...) instead of having the ActionLink handle it. If you're doing an HtmlHelper, like my example above is coming from, then I'd argue that calling ActionLink is an okay solution, or potentially better, is to use tagbuilder instead.
This is the only one that worked for me in .cshtml file:
#Html.ActionLink(
"Name",
"Action",
"Controller",
routeValues: null,
htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})
I hope this helps.

Categories