I am having a fat headache session with this following code, and was wondering if anyone can help me.
I have a view called Details.aspx, residing in a folder called project. Inside the details view, I have the following key code snippets which is causing me to get a headache.
<script type="text/javascript">
var Global_ProjectID = <%:Model.ProjectID%>; //Gets the project ID from Project Table In model
</script>
Inside a form tag (<form action="<%: ResolveUrl("~/Issue/AddIssue") %>" method="post">) resides the following code:
<p>
<input type="submit" class="submit small" value="Add Issue" onclick="return IssueSubmitForm()"/>
or <a href="">cancel</a></p>
And then I have some more Javascript to talk to my controller called IssueController, with the method called AddIssue
<script type="text/javascript">
var PostBackUrl = "<%:ResolveUrl("~/Issue/AddIssue")%>";
//Front-end Validation here
function IssueSubmitForm() {
var PostBackData = {
Title: $("input[name=Title]").val(),
Details: $("textarea[name=Details]").val(),
ReportedBy: $("input[name=ReportedBy]").val(),
Priority: $("select[name=Priority]").val(),
ProjectID: Global_ProjectID
};
$.post(PostBackUrl,PostBackData);
}
</script>
This gets the information entered into the form (from various web controls), and the value from the Global_ProjectID
In my controller, the following method is the one that is called from my javascript
[HttpPost]
public ActionResult AddIssue(Models.Issue issue)
{
Models.Issue newIssue = new Models.Issue()
{
Title = issue.Title,
DateLogged = DateTime.Now,
Status = 0,
ReportedBy = issue.ReportedBy,
Priority = issue.Priority,
ProjectID = issue.ProjectID,
};
return View("SomeOtherViewSomewhere");
}
Now here is the weird part.
All my fields (like title, reportedby etc.) gets filled as it should, i.e. It actually contains the value I expect it to contain- the data I filled into my form. ProjectID always happens to be null, when it should actually contain an integer value.
When I activated the debugger on my javascript in my browser, I saw that ProjectID did get populated, and in the event I added the following code Alert(Global_ProjectID);, it also gave me a popup with the value I needed.
However, the moment I run these code segments without debugging, ProjectID is always null. It is sadly a value that I must use recurringly, and null simply won’t do
What can I do to fix this code? I had other programmers look at it, and they were also just as stumped as I were.
I’d suggest looking into Javascript Scoping and Hoisting – JS doesn’t always behave in the way you expect with regard to the order in which variables and functions are initialised.
You can probably work around the issue by adjusting your
IssueSubmitFormfunction to acceptProjectIDas a parameter, and useonclick="return IssueSubmitForm(Global_ProjectID)"on your submit button…Or even better, remove the inline function call and bind a submit event after the page has loaded in the
$(document).ready()event.