MVC4 - Not executing the scripts js - c#

I'm trying to load the scripts for my application. Do not work so I checked a simple alert ('test11');. It also does not work, the script is not loaded at all?
It uses standard _Layout of MVC4 generated by Visual Studio 2013.
View Details.cshtml
#model xzy.Models.Album
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
#using (Html.BeginForm("Details", "Store", FormMethod.Post,
new
{
id = "someID",
data_oneAction = #Url.Action("one"),
data_twoAction = #Url.Action("two")
}))
{
<fieldset
<label for="Formats">Select format</label>
#Html.DropDownList("Formats", ViewBag.Formats as SelectList,
new { id = "FormatsID", #class = "xxx" })
<input type="submit" value="Submit" id="SubmitID" } />
</fieldset>
}
<script src="#Url.Content("~/Scripts/first_file.js")"></script>
<script src="#Url.Content("~/Scripts/second_file.js")"></script>
Script first_file.js
$(function () {
$('#FormatsID').change(function () {
alert('Test11');
});
});
UPDATE
Yaakov Ellis, it works. But when I have a script with the update, then it not works.
$(function () {
$('#FormatsID').change(function () {
alert('Test11');
var URL = $('#someID').data('oneAction');
$.getJSON(URL + '/' + $('#FormatsID').val(), function (data) {
alert('Test22');
});
});
});

The content of first_file.js is dependent on the presence of jQuery. I suspect that if you check your console log, you will see errors on the first line of this file.
This is confirmed by the fact that when you add in a jQuery reference prior to this file (as you wrote in your comment), it works.
So if you want to use this script as-is, be sure to include jQuery first.
If you just want a better test of the first_file.js file, then remove all of the jQuery stuff from it. Its sole contents should be one line with alert('Test11'); on it.

Related

How to render controller data in asp. net view

I have a web app in which has the following features:
Extract data from an MS Excel file
Process the data and store it in data structures based on certain criteria.
Pass the data structures from the controller to the view where they can be rendered.
The issue I'm having occurs with the first few steps. On my view page, I have a button where the user can upload the excel file. Once they click submit, a POST request is sent to transmit the file to the controller action (I'm using the index action for this which I'm not sure is correct) where the data is extracted from the file. Once the file is processed, I want to display the extracted data back on the same page as the upload button.
I've tried to implement this first by creating a class in the controller which is instantiated for each excel row and then each row is stored in one of three different lists of objects.
I then stored each of these lists in the ViewBag object:
//Handle POST request and determine in the file uploaded was of correct type
List<Dictionary<string, string>> dictionary = new List<Dictionary<string, string>>();
bool isSuccess = true;
int colID = 0;
int colTier = 0;
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = "";
//string fileinitPath = "//app235wnd1t/equityfrontoffice/INGDS/TierBulkUpload/";
string fileinitPath = "C:/Users/chawtho/Desktop/";
Regex regex = new Regex("WTDA.+xlsx"); //find correct filename
if (match.Success)
{
fileName = (match.Value);
}
if (fileName != "")
{
Match match = regex.Match(file.FileName);
//Extract data from excel file and store in collections
ViewBag.inactive_subscriptions = inactiveSubscriptions;
ViewBag.active_subscriptions = activeSubscriptions;
}
return View();
}
In the view I have the following:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
random text
#using (Html.BeginForm("Index", "Subscription", FormMethod.Post, new { enctype = "multipart/form-data" })) {
<fieldset class="form">
<legend>Upload Document</legend>
<input type="file" name="UploadedFile" id="FileUpload" required />
<input type="submit" name="Submit" value="Upload" />
<label id="saveStatus" style="color: red">
</label>
</fieldset>
}
#{
<li>#ViewBag.inactive_subscriptions[0].ID</li>
}
Here, I'm simply trying to read the ID field of the first object in the list of Subscriptions but I get the error:
Cannot perform runtime binding on a null reference
I'm not sure where this error is coming from because when I debug the controller code, the Viewbag is populated with the two lists before the View() is returned. I also tried moving the Subscription Class from the controller to a model class and created a container to hold the list of subscriptions but that didn't resolve the issue.
I think the problem might have something to do with the fact that the code the print the viewbag data is present when the page initially loads but I'm not sure if/how it should be kept from running until the file is processed.
How should I go about structuring this mvc setup to implement what I have outlined?
I put the next example, this is the way that I use to manipulate the excel files, notice that I don't use viewbag variables, this could be an option, like I've said I return the processed data into a json object and then I manipullate it via javascript.
-- Razor ViewPage
<!--Upload File-->
#using (Html.BeginForm("ProcessExcelFile", "ControllerName", FormMethod.Post,
new { id = "formUploadExcel", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-4">
<label for="file">Excel File (.xls, .xlsx)</label>
<input type="file" name="file" id="file" required="required">
</div>
</div>
<br>
<button type="submit" class="btn btn-primary">Upload File</button>
}
-- JS Script
<script type="text/javascript">
$('form#formUploadExcel').unbind('submit').bind('submit', function () {
formdata = new FormData($('form#formUploadExcel').get(0));
$.ajax({
url: this.action,
type: this.method,
cache: false,
processData: false,
contentType: false,
data: formdata,
success: function (data, status) {
console.log(data);
},
complete: function () {
//code...
}
});
return false;
});
</script>
-- Controller
[HttpPost]
public JsonResult ProcessExcelFile(HttpPostedFileBase file)
{
// Process the excel...
var business = new BusinessLayer();
var data = business.ValidateExcel(file);
// Return the Json with the procced excel data.
return Json(data, JsonRequestBehavior.AllowGet);
}

Is there a "standard MVC" way of mixing Javascript and Razor?

I really dislike page loads, I think they detract from the user experience, so I'm trying to make my web application heavily AJAX-ified.
When the user clicks on "Add new", Javascript generates a form based on a model using Razor, with the following code:
<script type="text/javascript">
var strNewCategoryForm = '<div><i class="glyphicon glyphicon-folder-open rightfolderpadding"></i>#using (Html.BeginForm("AddCategory", "Password", FormMethod.Post, new { #class="newcategoryform", role = "form", id="[1]" })) { #Html.AntiForgeryToken() #Html.PasswordFor(m => m.Category_ParentID, new { type = "hidden", value = "0" }) #Html.PasswordFor(m => m.CategoryName, new { type = "text" }) <span class="btn-group groupalign"><i class="glyphicon glyphicon-save"></i>Save</span> }</div>';
</script>
The code works great, Razor is able to generate the form within the string, so I dont have any issues with making this work.
However, for code readability and ease of development, it's not that great.
I'm still quite new to MVC and razor, so I'm just wondering, is there a better or "MVC/Razor standard" way of doing this, that I don't know about?
Edit:
In case anyone is interested, I've used both bits of Exception's answers:
In the partial view:
#model Secure_Password_Repository.Models.Category
<div><i class="glyphicon glyphicon-folder-open rightfolderpadding"></i> \
#using (Ajax.BeginForm("AddCategory", "Password", new AjaxOptions { HttpMethod="post", OnFailure="" }, new { #class="newcategoryform", role = "form", id="[1]" }))
{
#: \
#Html.AntiForgeryToken() #: \
#Html.HiddenFor(m => m.Category_ParentID, new { value = "0" }) #: \
#Html.TextBoxFor(m => m.CategoryName) #: \
#: <span class="btn-group groupalign"><i class="glyphicon glyphicon-save"></i>Save</span> \
}</div>
In the main view:
<script type="text/javascript">
var strNewCategoryForm = '#Html.Partial("_NewCategoryForm")';
</script>
The "\" at the end of each line in the partial view tell JavaScript that each line is continuation of a string value.
Answer 1 :-
If You are so keen to AJAX-ify your web app then better way is to use Ajax helper in Asp.MVC such as
#Ajax.BeginForm() or #Ajax.ActionLink() and Helpers like #Html.Partial() ,
#Html.RenderPartial() etc. are also handy for asynchronously loading data.
Their Basic Usage(I m taking hypothetical example here) :-
#Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
#using (Ajax.BeginForm("Edit", "Cars", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess"
}, new { #id = "updateCarForm" })) { ..... }
Follow this link :- http://www.codeguru.com/csharp/.net/working-with-ajax-helper-in-asp.net-mvc.htm
Above link will be helpful for you to understand building Forms with Ajax Helpers.
and one thing more the way you are building forms with razor syntax in javascript is not at all a good option 'in my opinion'.
Answer 2 :-
A small demo how to build a completely ajax-ified form which donot require any page reload:
#using (Ajax.BeginForm("Index", "Home", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Mydiv" }, new { #id = "frm" , #style ="width:700px" }))
{
//Your HTML here
}
Make above View a Partial View say 'Index.cshtml' and then return it this way through Controller as :
Public ActionResult Index()
{
return PartialView("Index");
}
Making Partial Views and loading Partial views through Jquery is handy to make unobtrusive forms.
This is more of an HTML-thing than MVC/Razor, as you are essentially asking on how to embed templates into your website. AFAIK html doesn't Support templating out of the box just yet, so you'd Need some JavaScript for that (in your case right now, you're probably using jquery)
Most template engines like knockoutjs, handlebars, etc. (maybe even jquery) support embedding templates similar to this:
<script type="text/html" id="my_template">
<div>
<p>
My template
</p>
</div>
</script>
The browser would not render that html, but a JavaScript library would use it (optionally doing some runtime data-binding) and display it.
Note: you can obviously put the html from that template into a partial view:
_MyTemplate.cshtml:
<div>
<p>
My template
</p>
</div>
View:
<script type="text/html" id="my_template">
#Html.Partial("MyTemplate")
</script>
Most template engines also support loading templates asynchronously, in which case you just render them the partial view alone.
Hope this helps a little.

Hook javascript to dropdownlist change

¡Hola!
My current task is to have a page where, with a dropdownlist, a user can select a deck title. Once a title is selected, the page should postback with details on that deck.
Here's what I've got at the moment:
#model IEnumerable<SCATChartsMVC.Models.Charts_DeckList>
#{
ViewBag.Title = "Index";
if (IsPost) { ViewBag.Title = "We posted back!"; }
}
<h2>Index</h2>
#{ var list = ViewData.Model.Select(cl => new SelectListItem
{
Value = cl.RecNum.ToString(),
Text = cl.DeckTitle.ToString()
});
}
#using (Html.BeginForm("Details", "Charts_DeckList", FormMethod.Post))
{
#Html.DropDownList("deckTitles", list, "---------select---------")
<input type="submit" name="submit" value="Submit" />
#Html.ActionLink("Details", "Details", "Charts_DeckList", new { id = list.ElementAt(4).Text }, "")
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$("deckTitles").change(function () {
if ($("#deckTitles").val() != "") {
var test = {};
test.url = "/Charts_DeckList/Details";
test.type = "POST";
test.data = JSON.stringify($('#deckTitles').val());
test.datatype = "json";
test.contentType = "application/json";
test.success = true;
test.error = function () { alert("Error!"); };
$.ajax(test);
}
})
</script>
The input tag and ActionLink under Html.BeginForm were for my own testing purposes; the ActionLink works correctly if I specify the element. I'm hoping to be able to pass something similar back whenever a user clicks a selection, as opposed to whenever they hit the "details" button.
The submit input tag does not work. It does route properly to Charts_DeckList/Details, but the parameter in the action is always null.
I'm just getting into the whole MVC/Web rigamarole, so there's a lot I don't know that I'm not even aware I don't know. While I've seen a number of different resources on the internet suggesting different things, much of the web development jargon is lost on me at this point in time, and much of the way these things work under the hood is lost on me since VS seems to put together so much of it automagically.
Any pointers would be appreciated. Thank you.
barrick's suggestion below is correct!
I also had to move the script tags up into the BeginForm brackets, heads up.
You're not setting the ID of the DropDownList there, the first argument sets the name attribute of the dropdown (used to identify the value in the POST variable collection on server postback) - you'll need to add another argument to set the ID:
#Html.DropDownList("deckTitles", list, "---------select---------", new { #id = "deckTitles" });
You can then pick up the selected value in the jQuery as follows:
$("#deckTitles option:selected").val();

bing map does not load

Im doing a web application in C# and ASP.NET MVC4.
Im having a problem with loading a map on one of my view pages...
I have the map on my Details page and the you go from Index page to Details page.
This is some of my code:
<div id='myMap' style="position:relative; width:400px; height:400px;">
</div>
<div>
<input type="button" value="createWalkingRoute" onclick="createDirections();" />
</div>
<div id='directionsItinerary'> </div>
#section scripts{
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'mykey' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createWalkingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to walking
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.walking });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle, WA' });
directionsManager.addWaypoint(seattleWaypoint);
var redmondWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond, WA', location: new Microsoft.Maps.Location(47.678561, -122.130993) });
directionsManager.addWaypoint(redmondWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createWalkingRoute });
}
else {
createWalkingRoute();
}
}
getMap();
</script>
}
When you go first go on the Details page the map doesn't load. However if the page is then refreshed, then the map loads after. So to me this is some sort of loading problem. But after trying for few hours Im absolutely stuck.
Can anyone help? thanks
put the getMap() call into some place where it will be called after the page is loaded, for example the body onload event. If you are using jquery, $(document).ready().

How to change labels of a form with json and razor snytax in .Net MVC3

I'm trying to use json for my web page's globalization options.. id like to change the labels of my form just by using a little dropdownbox and without refreshing the whole page and more interesting part is i got more than two form in my view.
so far i have done this:
My Json:
public JsonResult Globalx(String incoming)
{
System.Globalization.CultureInfo Cult = new System.Globalization.CultureInfo(incoming, true);
System.Threading.Thread.CurrentThread.CurrentCulture = Cult;
System.Threading.Thread.CurrentThread.CurrentUICulture = Cult;
Resources.Global.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
Global.ResourceManager.GetResourceSet(Cult, false, true);
ViewData["Name"] = Global.Name;
ViewData["Surname"] = Global.Surname;
ViewData["Birth"] = Global.Birth;
String lnginfo = Resources.Global.Culture.TwoLetterISOLanguageName.ToString();
ViewData["Languages"] = new SelectList(myList, "Value", "Text", lnginfo);
return Json(ViewData, JsonRequestBehavior.AllowGet);
}
My View:
#model MyCustomers.Models.Customers
#{
ViewBag.Title = ViewData["NewCustomer"];
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
function changeLang() {
var lang = $("#LanguageBox").val();
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
// what should i do here to get my label's language changed?
})
}
}
</script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "LanguageForm" }))
{
<fieldset>
<legend>#ViewData["LanguagesTitle"]</legend>
#Html.DropDownListFor(x => x.SelectedLanguage, (SelectList)ViewData["Languages"], new { onchange = "changeLang()", id = "LanguageBox" })
</fieldset>
}
#using (Html.BeginForm("PeopleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "PeopleForm" }))
{
<fieldset>
<legend>#ViewData["SalesContract"]</legend>
<div>
<div class="Name">
#Html.Label(ViewData["Name"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Name)
</div>
<div class="Surname">
#Html.Label(ViewData["Surname"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Surname)
</div>
<div class="Birth">
#Html.Label(ViewData["Birth"].ToString()) <!--> AND HERE </!-->
#Html.EditorFor(x => x.People.Birth)
</div>
</div>
</fieldset>
}
No im not actually using this method im refreshing the whole page each time to change the language of my labels but some friend of mine told me it could be done without refreshing and the first thing that came in my mind was Json.. I dont know if its possible or not im just trying. Any other ideas are wellcome.
I think the title is a little confusing and im asuming my problem here is understood so if anyone can find a better title please attempt to fix it.
In your Json result you would need to identify each of the labels that you have provided the text for, say each label has a Json object:
Id: 'label1',
Text: 'Enter your first name'
You provide one of these objects for each label on your page in an array,
{Id: 'label1', Text: 'Enter your first name'},
{Id: 'label2', Text: 'Enter your second name'},
{Id: 'label3', Text: 'Enter your telephone number'},
Then you deal with each of these on the requesting end,
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
for(i = 0; i < data.length; i++){
$('#'+data[i].Id).Html(data[i].Text);
}
})
I'm not 100% sure that Html will be the best thing to use - there may be sub DOM elements created by MVC that would need to be taken into account in your selector.
If you wanted to stick to the method you're using now you'll need to hard code each of the assigned values one at a time.
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
$('#Name').Html(data['Name']);
$('#Birth').Html(data['Birth']);
})

Categories

Resources