mvc ajax dropdownlist value problems - c#

So I'm having problems with dealing with cascading dropdownlists. Everytime I would pick a value on the 1st dropdown the 2nd dropdown will be populated but "with the selected value from the first" at the top of the 2nd dropdown. Does that make sense? Following are the codes. I'm not sure if it's appending correctly, can't seem to find anything on firebug.
Any advice is appreciated.
Thanks!!
the view:
<script type="text/javascript">
$(function () {
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("1stLevel") %>').change(function () {
$.ajax({
url: '<%: Url.Action("Index","2ndLevelDetails") %>?1stLevelId=' + $(this).val(),
success: function (data) {
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("2ndLevelId") %>').html(data);
},
async: false
});
});
});
</script>
<div class="dropdown">
<%: Html.DropDownList("1stLevelDetails", new SelectList(Model.1stLevel, "1stLevelId", "1stLevelDescription"))%>
</div>
<div class="dropdown">
<%: Html.DropDownListFor(model => model.2ndLevelId, new SelectList(Model.NTEESecondaryCodes, "2ndLevelId", "2ndLevelDescription", Model.2ndLevelId))%>
</div>
the controller 2ndlevel that returns the list of options
public string Index(int 1stLevelId)
{
var ntee = new System.Text.StringBuilder();
foreach (2ndLevelDetails code in 2ndLevelDetails.Find2ndLevelIds(ArgentDb, 1stLevelId))
{
ntee.AppendFormat("<option value=\"{0}\">{1}</option>", code.2ndLevelId, code.Description);
}
return ntee.ToString();
}

Try using jquery's live binder ..
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("1stLevel") %>').live('change', function () {
// ... code here
I've had to use live to bind to the change event since I can remember.. I don't know why.

Related

asp.net mvc if else not working in view

This is my part of code from view called index
<div class="box-body">
#{ Html.RenderAction("_BlogsGrid",new {country=""});}
</div>
...
...
<script>
$("#SelectedCountry").change(function () {
var selectedCountry = $(this).val();
$.ajax({
url: '#Url.Action("_BlogsGrid","Blog")' + '?country=' + selectedCountry,
sucess: function(xhr, data) {
console.log('sucess');
},
error: function (err) {
console.log(err);
}
});
});
</script>
Here is the controller action code
public ActionResult _BlogsGrid(string country)
{
var blogs = _blogService.GetBlogWithCountryName(country).ToList();
var blogsList = BlogMapper.ToBlogIndex(blogs);
return PartialView(blogsList);
}
and here is _BlogsGrid view
#model Blog.BlogsList
<div class="pull-right">
#Html.DropDownListFor(m => m.SelectedCountry, new SelectList(Model.CountriesList), "Select a country", new { #class = "form-control" })
</div>
<br />
<br />
#if (Model.Blogs.Count == 0)
{
<div class="box-group">
<h4>Sorry we couldn't find any blog related to the country you asked for.</h4>
#Html.DisplayText("Hello world!")
</div>
}
else
{
<div class="box-group" id="accordion">
#foreach (var blog in Model.Blogs)
{
#*Some code*#
}
</div>
}
Thing is when i load it first time everything works fine, the controllers method gets hit and all the blogs get loaded this is how the view looks
but when I select a country from dropdown list and there are no blogs matching that country
it hits the if condition(putting a breakpoint in view I check if if condition is being executed or else condition is being executed, and it goes through if condition) in view (which is a partial view)
but the content of "if" is not loaded in the browser.
I am still getting same content as before. Any idea why my content is not being updated?
Update:
<div id="grid" class="box-body">
#{ Html.RenderAction("_BlogsGrid",new {country=""});}
</div>
<script>
$("#SelectedCountry").change(function () {
var selectedCountry = $(this).val();
$.ajax({
url: '#Url.Action("_BlogsGrid","Blog")' + '?country=' + selectedCountry,
sucess: function (data) {
$('#grid').html(data);
},
error: function (err) {
console.log(err);
}
});
});
</script>
in browser response
But still my div is not updating.
As others suggested, you're not updating your div content. That's way yo don't notice a change when the AJAX call is completed.
To ease things, in addition to .ajax(), jQuery provides the .load() method, which automatically fed the returned content into the matched elements. So your javascript could look like so:
<script>
$("#SelectedCountry").change(function () {
var selectedCountry = $(this).val();
$("div.box-body").load('#Url.Action("_BlogsGrid","Blog")', 'country=' + selectedCountry);
});
</script>
Your ajax success function does nothing with the server response. It just print success in the browser console.
You need to use the server response on the success function and replace the atual content of the page with the new content.
Your html response is the first argument from success function.
You can look at jquery documentantion for better undertanding (http://api.jquery.com/jquery.ajax/)
To replace the content of your page the success function should be like that:
sucess: function(data) {
$("div.box-body").html(data);
console.log('sucess');
},
When the page is created, Razor replace all # by their value to generated the whole HTML page. This is why in debug mode, your #Html.DisplayText is hit.
However, when you load the page, the if is taken into account, and if the condition is false, you don't see the inner HTML.
To update your DOM, you have to use the data parameter of the success ajax call. This parameter is automatically set by the return of your _BlogsGrid method.
You can see it by modifying your success callback. Note that the data parameter should be the first parameter
sucess: function(data) {
console.log(data);
},
You're not updating the data after the initial load. Your ajax call returns the html content of your partial view. You'd have to update it to the DOM manually. Give your container div an id.
<div id="blogs-grid" class="box-body">
#{ Html.RenderAction("_BlogsGrid",new {country=""});}
</div>
And then in your ajax success callback:
sucess: function(data) {
$('#blogs-grid').html(data);
},
Now whatever content your ajax returned will be bound to the blogs-grid div

Simplest way to get model data/objects in the view from input with an ajax partial view call(s)

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>
}

Get value from ${xxx} into actionlink

In this project one of our programmers have written this code.
.
.
.
<script type="text/javascript">
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
schema: {
data: "Data",
total: "Total"
},
transport: {
read: {
url: '#Url.Action("List", "Customer")',
dataType: "json",
type: "POST"
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#listView").kendoListView({
dataSource: dataSource,
pageable: true,
template: kendo.template($("#customerTemplate").html())
});
$(".pager").kendoPager({
dataSource: dataSource
});
});
<script type="text/x-kendo-tmpl" id="customerTemplate">
<article>
**<h3>${CustomerNumber} ${FullName}</h3>
***<h3>${CustomerNumber} #Html.ActionLink(${CustomerNumber}, "Details", "Customer", new {id=${CustomerNumber}}, null)</h3>
<div class="details">
<span class="phone" itemprop="telephone">${Phone}</span>
<span class="email">${Email}</span>
</div>
<div class="clearfix"></div>
</article>
If you take a look at where the two stars are, that's the original code.
My task right now is to translate that code somewhow into a working code as the one where the three stars are. But, no matter how I try, I can't get the values from jquery thing (${CustomerNumber}, ${FullName}) and into the actionlink.
I can barely understand this (newbie, only three months with MVC), so please try and keep it simple for me if you can.
I actually tried to put this code where the article tag is and the call it as #fullname to no avail.
#string fullname = ${FullName}
I have tried to search SO and Google, but to be honest, I do not even know how to pose the question. Is this related to jquery or kendo? Is it even possible to achieve what I want?
Regards, S
Razor code is rendered server side therefore once the page is loaded any new razor code pulled via JavaScript won't render correctly.
There are ways around this though, one option would be to pull the template from the server so you could pre-render the view before it comes down and then let Kendo do it's mapping.
However, if you want to keep it all client-side, you could have a JS helper method which renders during the page load, in which you can run the razor code e.g.
<script type="text/javascript">
$(document).ready(function () {
function getCustomerUrl(linkText, customerNumber) {
var urlTemplate = '#Html.ActionLink("linkText", "Details", "Customer", new { id="customerNumber" }, null)';
return urlTemplate.replace('linkText', linkText).replace('customerNumber', customerNumber);
}
...
});
</script>
Then in your template simply call that method with the relevant parameters i.e.
<script type="text/x-kendo-tmpl" id="customerTemplate">
<article>
<h3>#= getCustomerUrl(FullName, CustomerNumber) #</h3>
<div class="details">
<span class="phone" itemprop="telephone">${Phone}</span>
<span class="email">${Email}</span>
</div>
<div class="clearfix"></div>
The short of it is you cannot do what you want to do. One thing to keep in mind is that all the code that is written in the view is processed on the server.
You are using javascript which gets processed on the client. The reason its not showing is your template has no idea what #Html.ActionLink(${CustomerNumber}, "Details", "Customer", new {id=${CustomerNumber}}, null) is. So you have a bit of a mismatch.
The question I would pose is, if this is working why do you need to change it?
Update base on comments
I would suggest this
<script type="text/javascript">
$(document).ready(function () {
var url = #Html.Action("Details", "Customer");
...
});
Then in your template this
<h3>${CustomerNumber} ${FullName}</h3>

Display a loading screen using anything

I sometimes have operation that takes a while to compute. I would like to be able to display something, like a kind of grey layer covering everything, or a loading screen, while the operation computes. But I frankly have no idea how to do it.
I'm building an MVC app using MVC4, I'm beginning with jQuery and opened to any suggestions. How might I do that?
EDIT
Here's a sample of page I've been building:
<h2>Load cards</h2>
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function (event) {
event.preventDefault();
alert("event prevented"); // Code goes here
//display loading
$("#loadingDialog").dialog("open");
alert("dialog opened"); // Never reaches here.
$.ajax({
type: $('#myForm').attr('method'),
url: $('#myForm').attr('action'),
data: $('#myForm').serialize(),
accept: 'application/json',
dataType: "json",
error: function (xhr, status, error) {
//handle error
$("#loadingDialog").dialog("close");
},
success: function (response) {
$("#loadingDialog").dialog("close");
}
});
alert("ajax mode ended");
});
});
</script>
#using (Html.BeginForm())
{
<div class="formStyle">
<div class="defaultBaseStyle bigFontSize">
<label>
Select a Set to import from:
</label>
</div>
<div class="defaultBaseStyle baseFontSize">
Set: #Html.DropDownList("_setName", "--- Select a Set")<br/>
</div>
<div id="buttonField" class="formStyle">
<input type="submit" value="Create List" name="_submitButton" class="createList"/><br/>
</div>
</div>
}
Here's a snippet of code from my javascript file:
$(document).ready(function ()
{
$(".createList").click(function() {
return confirm("The process of creating all the cards takes some time. " +
"Do you wish to proceed?");
});
}
As a bonus (this is not mandatory), I'd like it to be displayed after the user has confirmed, if it is possible. else I do not mind replacing this code.
EDIT
Following Rob's suggestion below, here's my controller method:
[HttpPost]
public JsonResult LoadCards(string _submitButton, string _cardSetName)
{
return Json(true);
}
And here's the "old" ActionResult method:
[HttpPost]
public ActionResult LoadCards(string _submitButton, string _setName)
{
// Do Work
PopulateCardSetDDL();
return View();
}
As of now the code never reaches the Json method. It does enter the ajax method up there (see updated code), but I don't know how to make this work out.
We hide the main content, while displaying an indicator. Then we swap them out after everything is loaded. jsfiddle
HTML
<div>
<div class="wilma">Actual content</div>
<img class="fred" src="http://harpers.org/wp-content/themes/harpers/images/ajax_loader.gif" />
</div>
CSS
.fred {
width:50px;
}
.wilma {
display: none;
}
jQuery
$(document).ready(function () {
$('.fred').fadeOut();
$('.wilma').fadeIn();
});
First you want to have jQuery "intercept" the form post. You will then let jQuery take care of posting the form data using ajax:
$("form").submit(function (event) {
event.preventDefault();
//display loading
$("#loadingDialog").dialog("open");
$.ajax({
type: $('#myForm').attr('method'),
url: $('#myForm').attr('action'),
data: $('#myForm').serialize(),
accept: 'application/json',
dataType: "json",
error: function (xhr, status, error) {
//handle error
$("#loadingDialog").dialog("close");
},
success: function (response) {
$("#loadingDialog").dialog("close");
}
});
});
More information on the $.ajax() method is here: http://api.jquery.com/jQuery.ajax/
You could use the jquery dialog to display your message: http://jqueryui.com/dialog/
There are other ways to display a loading message. It could be as simple as using a div with a loading image (http://www.ajaxload.info/) and some text, then using jQuery to .show() and .hide() the div.
Then, in your controller, just make sure you're returning JsonResult instead of a view. Be sure to mark the Controller action with the [HttpPost] attribute.
[HttpPost]
public JsonResult TestControllerMethod(MyViewModel viewModel)
{
//do work
return Json(true);//this can be an object if you need to return more data
}
You can try creating the view to load the barebones of the page, and then issue an AJAX request to load the page data. This will enable you to show a loading wheel, or alternatively let you render the page in grey, with the main data overwriting that grey page when it comes back.
This is how we do it in our application, however there is probably a better way out there...
if not I'll post some code!
EDIT: Here's the code we use:
Controller Action Method:
[HttpGet]
public ActionResult Details()
{
ViewBag.Title = "Cash Details";
return View();
}
[HttpGet]
public async Task<PartialViewResult> _GetCashDetails()
{
CashClient srv = new CashClient();
var response = await srv.GetCashDetails();
return PartialView("_GetCashDetails", response);
}
Details View:
<div class="tabs">
<ul>
<li>Cash Enquiry</li>
</ul>
<div id="About_CashEnquiryLoading" class="DataCell_Center PaddedTB" #CSS.Hidden>
#Html.Image("ajax-loader.gif", "Loading Wheel", "loadingwheel")
</div>
<div id="About_CashEnquiryData"></div>
<a class="AutoClick" #CSS.Hidden data-ajax="true" data-ajax-method="GET"
data-ajax-mode="replace" data-ajax-update="#About_CashEnquiryData"
data-ajax-loading="#About_CashEnquiryLoading" data-ajax-loading-duration="10"
href="#Url.Action("_GetCashDetails", "Home")"></a>
</div>
Custom Javascript:
$(document).ready(function () {
// Fire any AutoClick items on the page
$('.AutoClick').each(function () {
$(this).click();
});
});

MVC3 C# Entity Framework populate textbox based off dropdownlist selection

Couple of links I've tried, that led me to my code... which isn't working :D
Get The Drop on DropDownLists and
Creating Cascading Dropdown Lists
I am trying to allow the user to select a part number (itemnmbr) from a dropdown list and upon their selection, have the page refresh the part description (itemdesc) textbox with the correct value. Below is the closest I've gotten.
VIEW CODE:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ITEMNMBR").change(function () {
$.get("/PartsLabor/GetPartDesc", $(this).val(), function (data) {
$("#ITEMDESC").val(data);
});
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Add part to call: #ViewBag.CALLNBR</legend>
#Html.LabelFor(model => model.ITEMNMBR, "Item Number")
#Html.DropDownList("ITEMNMBR", (SelectList) ViewBag.Items, "Please Select a Part #")
#Html.ValidationMessageFor(model => model.ITEMNMBR)
<br />
#Html.LabelFor(model => model.ITEMDESC, "Description")
#Html.EditorFor(model => model.ITEMDESC)
#Html.ValidationMessageFor(model => model.ITEMDESC)
<br />
<input type="submit" class="submit" value="Add Part" />
</fieldset>
}
Controller Code:
[Authorize]
public ActionResult PCreate(string call)
{
var q = db.IV00101.Select(i => new { i.ITEMNMBR});
ViewBag.Items = new SelectList(q.AsEnumerable(), "ITEMNMBR", "ITEMNMBR");
ViewBag.CALLNBR = call;
return View();
}
public ActionResult GetPartDesc(char itemnmbr)
{
var iv101 = db.IV00101.FirstOrDefault(i => i.ITEMNMBR.Contains(itemnmbr));
string desc = iv101.ITEMDESC;
return Content(desc);
}
Firefox Error Console returns:
Timestamp: 12/28/2012 2:40:29 PM Warning: Use of attributes' specified
attribute is deprecated. It always returns true. Source File:
http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.4.min.js Line: 2
Timestamp: 12/28/2012 2:40:34 PM Warning: Use of getAttributeNode() is
deprecated. Use getAttribute() instead. Source File:
~/Scripts/jquery-1.6.4.min.js Line: 3
Firefox Web Console returns those two, as well as the below (which lands between the above two):
Request URL: ~/PartsLabor/GetPartDesc?002N02337
Request Method: GET
Status Code: HTTP/1.1 500 Internal Server Error
I think you are on the right track. Check out the examples on this page on how to use get().
guessing GetPartDesc is never getting hit or it's not getting the parameter that you are expecting. It will probably work if you change:
$.get("/PartsLabor/GetPartDesc", $(this).val(), function (data) {
$("#ITEMDESC").val(data);
});
to:
$.get("/PartsLabor/GetPartDesc", { itemnmbr: $(this).val() }, function (data) {
$("#ITEMDESC").val(data);
});
But I haven't tested it. Also I personally use the jquery .ajax method for this kind of thing. I've never used get, though reading a little seems like what you have should work. Anyway you can try something like this:
$.ajax({
url: '/PartsLabor/GetPartDesc',
data: { itemnmbr: $(this).val() }
}).done(function (data) {
$("#ITEMDESC").val(data);
});

Categories