I have JavaScript code :
<script>
function ChangeRegion()
{
var countryId = document.getElementById("country").value;
}
</script>
I have textbox on my view:
#Html.DropDownListFor(m => m.Register.SelectCountryId, Model.Register.Country, "Select country", new { id = "country", #class = "form-control",#onchange="ChangeRegion();" })
Now i need on change to pass value to my controller to get Regions
my controller:
model.Register.Region = new SelectList(manager.GetRegions(model.Register.SelectCountryId), "Id", "Name");
EDIT: this is my controller for post :
when i choose country and click submit button i get values for raegions but i need to get values without submiting form
model.Register.Country = new SelectList(manager.GetCountries(), "Id", "Name");
model.Register.Region = new SelectList(manager.GetRegions(model.Register.SelectCountryId), "Id", "Name");<-- i want to put here that id from javascript
model.Register.WebTypeOfLicense = new SelectList(CommonDbService.GetAllLicense(), "Id", "Name");
model.Register.City = new SelectList(manager.GetCities(model.Register.SelectRegionId), "Id", "Name");
return View(model);
Here is an example of using Ajax Post using your function,
This will post the value from your HTML element to the GetData action on the Home controller. Once it has reach the GetData method it will return it and show the alert on the client.
function ChangeRegion() {
var countryId = document.getElementById("country").value;
$.post('/Home/GetData', { 'CountryId': countryId }, function (d) {
alert(d);
}, 'json');
}
This code is in my HomeController,
public JsonResult GetData(int CountryId)
{
return Json(CountryId);
}
Sorry if this isn't clear enough, if you need more direction just post some of your code, like controller & action names.
Thanks
Related
I have a Kendo DropDownList on the View and I want to pass its DataTextField value to the Controller and then pass and them on the labels in another View. Although I can pass DataValueField values to the Controller, I cannot pass DataTextField values. I tried to apply different scenarios but I could not. Any idea? On the other hand, if it is not possible, should the DataTextField values be populated again on the Controller and return to the other View?
View:
#model IssueViewModel
...
#Html.LabelFor(m => m.ProjectID)
#(Html.Kendo().DropDownList()
.Name("ProjectID")
.DataTextField("ProjectName")
.DataValueField("ProjectId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProjects", "Issue");
});
})
)
Controller:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new { ProjectId = m.ID, ProjectName = m.Description }), JsonRequestBehavior.AllowGet);
}
/* I want to pass the DataTextField values to this
method and return them to the CreateManagement view */
public ActionResult Create(IssueViewModel issueViewModel)
{
return RedirectToAction("CreateManagement", issueViewModel);
}
Change your controller to this:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description, ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
}
Since the DropDownList uses DataTextField for the user and uses DataValueField for the server communications, so you have to use DataTextField value for both. Then you can use it for the next operations.
Edit: if you need both values on the controller, change JsonResult method to :
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description + "," + m.ID , ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
Now you can use both in the next operations just by spiting them like:
var _both = value.split(',');//value: returned value from the view
I will put a "Choose Civil Status" parameter inside a POST method in my Swagger-UI, so instead of a text fields I wanted it to be a drop down list, I'm using MVC 3, Can anyone explain how can I do that?
here is my sample code..
[HttpPost]
public string Generate(string id, Salutation Salutation)
{
//code here
}
Inside the controller put
var Users = db.TABLENAME;
List<ListItem> list = new List<ListItem> ();
list.Add(new ListItem("Please Select", "0"));
foreach (var item in Users)
{
list.Add(new ListItem(item.ColName , item.UserId.ToString()));
}
ViewBag.UserList = new SelectList(list, "ValueField", "TextField");
In View
#Html.DropDownList("SomeName", (SelectList)ViewBag.UserList , new { #class = "DropDownList W150 ", value = #ViewBag.SelectedVal })
and you will have to declare your ListItem in ModelClasses
I have a json string like [{Name:"Russia",Value:6},{Name:"USA",Value:"8"}]
in controller how can i convert this list to select list item to bind to a dropdownlist?
and i have to populate state list depending upon the selected country using ajax post back?
anybody give some sample on this
Below is example for bind dropdown from your json object. In this example GetCountry is function from controller which is return json object and below script is iterate json object and bind the dropdown.
Script:-
$(document).ready(function () {
$.getJSON('#Url.Action("GetCountry", "Dropdown")', function (result) {
var ddlCountryId = $('#CountryId');
ddlCountryId.empty();
$(result).each(function () {
ddlCountryId.append(
$('<option/>', {
value: this.Id
}).html(this.Nome)
);
});
});
});
View syntax:-
#Html.DropDownListFor(x => x.CountryId, new SelectList(Enumerable.Empty<SelectListItem>()))
Controller Function:-
public ActionResult GetCountry()
{
var sites = new[]
{
new { Id = "6", Nome = "Russia" },
new { Id = "8", Nome = "USA" }
};
return Json(sites, JsonRequestBehavior.AllowGet);
}
I am attempting to create a cascading dropdown. My Controller looks like this to initialize the view..
public ActionResult Create()
{
var model = new RoundDetailViewModel();
model.AvailableFacilities = new SelectList(db.Facilities, "FacilityId", "Facility_Name");
model.AvailableCourses = new SelectList(Enumerable.Empty<Course>(), "CourseId", "Course_Name");
model.AvailableTeeTypes= new SelectList(Enumerable.Empty<TeeType>(), "TeeTypeId", "Name");
return View(model);
}
This will populate the first dropdown, and also create 2 empty dropdown as expected.
Now on a selection of the first dropdown I want to call an Action in my controller to populate the second dropdown. This is where I am a little foggy on the code in the action to populate the second dropdown. I want to use something like this to trigger calling the action..
$("#ddlFacility").change(function () {
var selectedFacility = $(this).val();
if (selectedFacility != null && selectedFacility != '') {
$.getJSON("#Url.Action("GetCourse")", { facility: selectedFacility }, function (courses) {
var coursesSelect = $('#ddlCourse');
coursesSelect.empty();
$.each(courses, function (index, course) {
coursesSelect.append($('<option/>', {
value: course.value,
text: course.text
}));
});
});
}
});
public ActionResult Courses(int facilityId)
{
//WHAT GOES HERE TO POPULATE SELECT LIST??
}
Need to return JsonResult and allow Get (if that is what you decide to do) Alternatively you need to make it a POST and do a POST to it.
Something like
public JsonResult GetCourses(int id)
{
var Courses= db.Courses.Where(a=>facilityId==id).ToList();
SelectList list = new SelectList(Courses,"Text", "Value");
return Json(list , JsonRequestBehavior.AllowGet);
}
My Controller:-ForumController
Action:Topic
ViewPage to pass parameter is
<%= Html.ActionLink("Topic", "Topic", "Forum", new { userid = "1" }, null)%>
Controller
public ActionResult Topic(String userid)
{
var topics = new topic { userId = userid };
return View(topics);
}
The parameter is getting passed but instead of getting URL Forum/Topic/1,I am getting Forum/Topic?userid=1;
Can anyone help me out
I suspect that you used the default route in Global.asax in which you have {controller}/{action}/{id}.
So you should use the same name (id):
<%= Html.ActionLink("Topic", "Topic", "Forum", new { id = "1" }, null)%>
and then:
public ActionResult Topic(String id)
{
var topics = new topic { userId = id };
return View(topics);
}
If you don't want to use {id} but some other token make sure you adjust your routes accordingly.