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>
Related
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.. :)
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 am working on an asp.net webapp, and in a view I have a drop down list that the user can select a value from. The drop down list works just fine-the right text is displayed in the menu. But, when I try and use some basic JS to capture the value, I get
"Uncaught TypeError: Object # has no method 'GetElementById' " in the JS Console in Chrome. Here is my code:
<select id="stop" onchange="sendInfo();">
#foreach(var blah in ViewBag.foobar)
{
<option value=#blah>#blah</option>
}
</select>
<script>
function sendInfo() {
var stopId = document.GetElementById("stop").value;
}
</script>
Any help would be appreciated, I am very new to MVC and asp.net stuff.
Thanks,
Amanda
JavaScript is a case sensitive language and the method what your are looking for is getElementById
So you should write:
var stopId = document.getElementById("stop").value;
You don't need to call getElementById function, you can access html element by event object which passed to each event handler:
<select id="stop" onchange="sendInfo(event);">
#foreach(var blah in ViewBag.foobar)
{
<option value=#blah>#blah</option>
}
</select>
<script>
function sendInfo(event) {
var stopId = event.target.value;
}
getElementById...
Case sensitivity matters.
I am quite new to this net mvc thing. to understand what I am trying to do I will put an example.
Example
I have a list of clients that contains data and in my view I used a <select> with a foreach that goes through all the clients to show the data. What I am trying to do is, when a user selects a client name he would be redirected to another page where that page would get the client name as a parameter & do stuff with that.
I tried this but I am stuck in a part
<select>
#foreach (var item in Model.clients)
{
<option>
#Html.Encode(item.name)
</option>
}
</select>
I know how to redirect from page A to page B like this RedirectToAction(...) what I want to do is handle that select action to call the method in my controller & use that method to send a parameter to page B
UPDATE
<script type="text/javascript">
function Fct() {
var v = arguments[0]; //get The ID in the parameter
window.location.href = "#Url.Action("Index", "PageB")?client_id=" + v;
}
</script>
I tried both lists and the one proposed by #Shyui is easier but i wanted to try something with this one
<select id="clients_list" onchange="Fct(this.value)">
<option class="placeholder" selected disabled value="-1">Select Name</option> <!-- Can't be selected -->
#foreach (var item in Model.clients)
{
<option value="#item.ID">
#Html.Encode(item.name)
</option>
}
<option value="0">New Client</option>
</select>
Listen to the change event of the dropdown, get the selected option and redirect the user to the next action.
<select id="Clients">
#foreach (var item in Model.clients)
{
<option value="#item.name">#Html.Encode(item.name)</option>
}
</select>
Here is the javascript(using jQuery) to handle the change event
$(function(){
$("#Clients").change(function(){
var v=$(this).val();
window.location.href="#Url.Action("Details","Clients")?clientName="+v;
});
});
I am using the Url.Action helper method to generate the correct relative path to the action method. This will work if your code is inside a razor view. But if it is inside an external js file, try the solution explained in this answer.
Assuming your Details action method in ClientsController accepts a client name
public ActionResult Details(string clientName)
{
// to do : Return something
}
You might also consider using the html helper methods like Html.DropdownList to generate the dropdown element instead of doing a foreach.
#Html.DropDownList("Clients",new SelectList(Model.clients, "name", "name"))
Also you might consider passing the unique client Id(numeric) instead of the client name. There are limitations of query string value length in some browsers.