Hello guys i hope you all are doing great, so i am working on a project with my buddy but we both are intermediate programmers and stuck into a place so i need your help...
the problem is I'm stuck in a certain code which is for "search the dish":
ShowAll list page
After selecting value from a combo box
it's doing post back from java script method as you can see in the picture but i think my code is incomplete because i can't get value from database i is showing the list on my "ShowAll page" but when i choose a value from combo box it doesn't show anything..
ActionResult Code
public ActionResult ShowAll()
{
var a = from tb in me.RecipeTables select tb;
return View(a.ToList());
}
[HttpPost]
public ActionResult ShowAll(string searchDish)
{
var k = me.RecipeTables.Where(l => l.recipeName == searchDish);
return View(k);
}
View Code wit java script function
<html>
<script type="text/javascript">
function SelectedIndexChanged()
{
this.myForm.submit();
}
</script>
<%using (Html.BeginForm("ShowAll", "RecipeView", FormMethod.Post, new { id = "myForm", name = "myForm", enctype="multipart/form-data"}))
%>
<p>
<%: Html.ActionLink("Create New", "Create") %>
<select id="searchDish" name="searchDish" onchange="SelectedIndexChanged()">
<option value="0">Select any</option>
<option value="1">biryani</option>
<option value="2">fried rice</option>
<option value="3">Nihari</option>
<option value="4">Tikka</option>
</select>
</p>
need help!!! thanks in advance
For this functionality you need to add Ajax call on OnChange of searchDish
but you need to add in your code for return result
Note : for this functionality you need to add JQuery libraries in your code.
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
Ajax Call :
$('#searchDish').change(function () {
var vid = $("#searchDish").val();
$.ajax({
url: "/RecipeView/ShowAll?id=" + vid,
type: "POST",
dataType: "html",
data: 'json',
async: false,
success: function (data) {
$('#divLanguage').html(data);
}
});
});
Cheers !!
the problem was with the i was sending string value in constructor and retrieving in numbers so i just changed it to and you can even do this that don't give any value it will work.. :)
Related
The autocomplete code written is getting the results from controller and is also showing when used F12 developer network tab with the browser. But the actual returned result is not showed by the textbox, only drop-down with no values are shown.
I'm including the codes of view and controller. Please help me out to solve this.
code of the view page :
<html>
<head><title></title>
<link href="~/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet" />
<script type="text/javascript" >
$(document).ready(function () {
alert("hi");
$("#ValueField").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Customer/AutoretrieveCustomer",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
var items = $.map(data, function (item) {
return {
label: item.FirstName,
value: item.FirstName
};
});
response(items);
}
})
}
});
});
</script>
</head>
<body>
<div id="CusView">
<label for="FirstName">Enter Customer First name : </label>
Enter value : <input type="text" id="ValueField" />
</div>
</body>
</html>
code of the controller :
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AutoretrieveCustomer(string term)
{
Banking.BankingDBEntities db = new BankingDBEntities();
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I would need the code for getting the id of the user selected item in the textbox.
The following the output pic when the autocomplete is executed
This bit in your controller action:
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
Means that your controller action is actually returning an array of strings, not an array of objects like your success function is assuming.
You should be able to remove the mapping and just call response directly with the array of strings:
success: function (data) {
response(data);
}
Or, just:
success: response
The application is in .Net framework 3.5 and MVC framework 2.0 for .Net framework 3.5. I have a view which in $.post passes parameters. I also need that $.post , passes model values to controller.
In the view below , how do I pass model in the $.post function, so that the controller gets the value of the Textbox. I need the button and not submit button.
The view is:
<div>
<label for ="Name"> Name</label> <%=#Html.TextBoxFor(m => m.Name) %>
<select id ="prod" style ="width:150px">
<option value ="GL">GL</option>
<option value = "Property"> Property</option>
<option value = "Package">Package</option>
<option value = "Island">Island</option>
</select>
<input type="button" id="btnPost" value = "GetValue" />
</div>
<script src="/Scripts/jquery-1.4.1.min.js" type ="text/javascript"></script>
<script type ="text/javascript" >
$(function() {
$("#btnPost").click(function() {
alert("here" + $("#prod").val());
$.post("/Transfer/DisplayText", { "str1": $("#prod").val()},
function(data) {
alert("success");
});
});
});
Th controller is:
[HttpPost]
public ActionResult DisplayText(string
str1,TestPost_AjaxMVC.ViewModels.TransferViewModel model)
{
string str2 = str1;
return View("Transfer");
}
The model is :
public class TransferViewModel
{
public string Name { get; set; }
}
I think everything is ok in your code just replace
$.post
to $.get
Because you are returning a view from your controller also use Url.action
like below because it may not work when you publish the project
$.get('<%=Url.Action("DisplayText","Transfer")%>', { str1: $("#prod").val()},
function(data) {
alert("success");
});
You should remove double quote from str1.Let me know if it does not work.
JSON.stringify the model and send it as part of data and let MVC use JSON Model Binding
$(function() {
$("#btnPost").click(function() {
var TransferViewModel={};
TransferViewModel.Name="SomeData";
var postData={};
postData.str1=$("#prod").val();
postData.model=TransferViewModel;
$.ajax({
url:"/Transfer/DisplayText",
type:"POST",
data:JSON.stringify(postData),
contentType:"application/json; charset=utf-8",
success: function(){
}
});
});
});
I am new to MVC and Javascript. I am trying to make a "change user info" page for admin. I have a dropdown which lists registered users and some textbox for enter various info about users (eg, name, surname). My objective is auto fill textboxes with users current info when selected an user with dropdownlist. But because of MVC is not event driven and doesn't have postback I don't exactly know how to accomplish this. I think I have to trigger a controller method by dropdownlist's onchange and I think the only way is using JS, AJAX or something like these.
Note: I can do all database stuff in Controller.
I have this code so far in my view:
.... #Html.DropDownList("Users", ViewBag.Users as SelectList, "Select a User", new { id="UserId", onchange="userChanged()"} ) ....
.... <script type="text/javascript">
function userChanged() {
}
</script> ....
You can define your controller action method as JsonResult and call it from your jquery using AJAX.
Once you get data using AJAX, you can parse it and fill appropriate textbox with that data.
you can use below code on how to call ajax in you userChanged method:
$.ajax ({
url: '/Controller/Action',
type: 'GET',
async: true,
cache: false,
data: { userId: useridofwhichdatatobefetched},
success: function (result) {
$("#usernametextbox").val = result.userName; }
});
$(document).ready(function(){
$("#UserId").change(function () {
if ($(this).val() != "" && $(this).val() != undefined && $(this).val() != null)
$.ajax({
type: "GET",
url: "/[ControllerName]/[ActionName]/" + $("#UserId").val()
})
.success(function (data) {
// 'data' consits of values returned from controller.
// fill textboxes with values in 'data'
});
});
});
Hope this helps you.
Try something like this (fiddle):
<select id="select1">
<option value="userId1">User 1</option>
<option value="userId2">User 2</option>
<option value="userId3">User 2</option>
</select>
<textarea id="txt1">
</textarea>
$(function(){
$('#select1').change(function(){
$.ajax({
url: "YourAction", // Url.Action()
data: {
userId: $(this).val()
},
success: function(data) {
$('#txt1').val(data);
}
});
});
});
I'm having a difficult time passing my Select values on my View to the controller.
I have two items on my view which I wish to return to the model, where I can call in the controller. Heres what I have so far.
<label for="phone" class="ui-hidden-accessible">Phone Number:</label>
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "field-margin", id="phone", type="tel", placeholder="Phone Number"})
<p></p>
<div><p>Save phone for future purchases?</p>
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false" #(Model.SavePhone == false ? "selected" : "")>No</option>
<option value="true" #(Model.SavePhone == true ? "selected" : "")>Yes</option>
</select><
I'm not exactly sure how to call the second part for the select options. However the top part of my code which accepts the phone number works. My naming in the model, controller, and view all are the same so I'm not sure what to do next. If you have any suggestions it would be appreciated.
Thanks!
Edit
I figured out a part of my problem, Since I am loading this as
#Html.Partial("MobilePhoneView", Model)
after I click continue on the first page, it loads the view with my two options and hits the select block before it even displays. Is there some kind of work around for this?
You can do this using AJAX. If you have following HTML
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
Then , you can simply use following to sent your choice to controller:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","ControllerName")',
type: 'POST',
cache: false,
data: { Selected: $("#SavePhone").val() },
success: function (data) {
//
}
});
});
)};
</script>
You will get this value in the controller
private string MethodName (string Selected)
{
String value = Selected;
return "OK";
}
The only possible problem with your code might be with selected attribute. Not all browsers understand just selected (I believe this is HTML5 way of setting such attributes), though all should understand selected="selected". So what you can try is:
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false" #(Model.SavePhone == false ? "selected=\"selected\"" : "")>No</option>
<option value="true" #(Model.SavePhone == true ? "selected=\"selected\"" : "")>Yes</option>
</select>
I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.