I have created a dropdownlist using html helper.
It's able to get the value and bind to dropdown.
How can i pass the selected dropdown value to controller?
My View:
#Html.DropDownList("Language", new SelectList(ViewBag.LangList, "Text", "Value"))
<input type="button" class="btn" title="Filter By Language"
value="Filter By Language" onclick="location.href='#Url.Action("SURV_Answer_Result", "SURV_Answer",
new { Survey_ID = Model[0].Survey_ID, Language = ViewBag.LangList })'" />
My Controller to get Language and bind into dropdown:
public ActionResult SURV_GetLanguage(int Survey_ID)
{
var getlanguagelist = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.Qext_Language into grp
select grp.FirstOrDefault();
foreach (var item in getlanguagelist.ToList())
{
List<SelectListItem> langResult = new List<SelectListItem>();
foreach (var item2 in getlanguagelist)
{
SelectListItem temp = new SelectListItem();
temp.Text = item2.r.Qext_Language;
temp.Value = item2.r.Qext_Language;
langResult.Add(temp);
}
ViewBag.LangList = langResult;
}
return View(ViewBag.Langlist) ;
}
And i want pass the Language to the controller below:
public ActionResult SURV_Answer_Result(int Survey_ID, string Language)
{
List<AnswerQuestionViewModel> viewmodel = new List<AnswerQuestionViewModel>();
SURV_GetLanguage(Survey_ID);
// do whatever i want...
}
Your button in the view istype="button" and you have attached a onclick event which will just redirect to the SURV_Answer_Result passing the original ViewBag property back to the method (which will not bind to string Language because its List<SelectListItem>.
You need a form with FormMethod.Get
#using (Html.BeginForm("SURV_GetLanguage", "ControllerName", new { Survey_ID = Model[0].Survey_ID }, FormMethod.Get))
{
#Html.DropDownList("Language", (Enumerable<SelectListItem>)ViewBag.LangList)
<input type="submit" ... />
}
Notes:
The Survey_ID has been added to the form as a route value
ViewBag.LangList is Enumerable<SelectListItem> which is all that
is required by the DropDownList() helper so there is no point in
the extra overhead of creating another SelectList from it
(SelectList IS Enumerable<SelectListItem>)
The code you have used would work if you change the method signature on the controller to public ActionResult SURV_GetLanguage(int Survey_ID, string Language = null). You could then test for nulls and process as necessary.
However it would be better to wrap the dropdownlist inside a form, and use a POST request. Something like:
#using (Html.BeginForm("SURV_GetLanguage","ControllerName",FormMethod.Post))
{
#Html.DropDownList("Language", new SelectList(ViewBag.LangList, "Text", "Value"))
<input type="submit" class="btn" />
}
Then in the controller you could have a new method:
[HttpPost]
public ActionResult SURV_GetLanguage(string Language)
{
//Do whatever you want with language.
}
There are two ways,
1) You can put your dropdown and submit button into a form containing action parameter. On button press, your form will be submitted to its action. Your action must contain a parameter with name 'Languages'. It will give you selected value.
All the parameters of action, if matching to 'name' property of controls, will contain their values on form submit.
2) You can get selected value from dropdown by using jquery and then use either window.location or build url for form's action and call submit.
Related
I have a simple view with a checkbox at the bottom:
#model Application.Areas.Cms.Models.ProduktBeispielViewModel
#{
ViewBag.PopupHeadline = "Produktbeispiele";
ViewBag.PopupSubHeadline = Model.Item != null ? Model.Item.NameInCurrentLang : "";
ViewBag.HideLanguageComparison = true;
}
#section TabMenu
{
<ul>
<li>Einstellungen</li>
<li>Bild</li>
</ul>
}
<form action="#Url.Action("SaveIndex")" method="POST" id="idForm">
#Html.HiddenFor(m => m.AutoCloseWindow)
#Html.HiddenFor(m => m.Item.Id)
<checkbox/>
</form>
I have this Index:
public ActionResult Index(int id = 0, int categoryId = 0, bool autoclosewindow=false,bool refreshOpener=false)
{
var model = LoadModel(id, categoryId);
model.AutoCloseWindow = autoclosewindow;
model.RefreshSequenceInOverview = refreshOpener;
foreach (var lang in new LanguageManager().GetItems())
{
...
}
return View(model);
}
And ofc I have my model containing the data properties.
I can already display values bound inside my model in my view but I cannot seem to go the way back, meaning if the user checks the checkbox, how do I retrieve that is has been checked?
(Same would go for an editor or entry field)
How can I access the data from my checkbox?
EDIT:
I already have a form of which the checkbox is a child:
<form action="#Url.Action("SaveIndex")" method="POST" id="idForm">
#Html.HiddenFor(m => m.AutoCloseWindow)
#Html.HiddenFor(m => m.Item.Id)
#Html.CheckBoxFor(m => m.Test2)
But when I set a stoppoint at the corresponding function:
public ActionResult SaveIndex(Product item, List<GeneralLanguageEntry> languages, bool autoclosewindow = false)
{
...
return RedirectToAction("Index", new { autoclosewindow = autoclosewindow, refreshOpener = true, id = productFromDb.Id });
}
The model is not returned here... So i cannot see my altered checkbox
You need to use a rendered control from the html helper rather than just putting a checkbox on the page. This will bind the control to the property in your model.
#Html.CheckBoxFor(m => m.YourBoolValue)
Make sure you have a method that will accept your post data when the form is submitted:
[HttpPost]
public ActionResult SaveIndex(Product item)
...
Is it possible to use Model binding to get value of a button in the POST action method when its clicked on. I have a complex type and I wanted to have the user click on a button and retrieve the value of that button so I can use it to update the value of the complex type in the DB.
Note that at this point I have already saved the entity into the database and all that is left is to get a way to update properties of the complex type.
If there is a recommended way to do that am willing to adopt that.
Thanks in advance.
You can use multiple submit buttons with different values to specify the way of update model.
#using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
{
.
.
.
<button type="submit" id="btnSave" name="Command" value="create">Save</button>
<button type="submit" id="btnSubmit" name="Command" value="update">Submit</button>
}
public ActionResult(ComplexModel model, string Command)
{
if(Command == "create")
{
}
else if(Command == "update")
{
}
else
{
// Default action
}
}
For more info read Handling multiple submit buttons on the same form - MVC Razor.
Do something like this
public ActionResult Index(string submit)
////Your action while clicking the button and in the view button name should be submit
{
//// The string submit will have the value of the button
}
I have 2 radio buttons with mvc view.When i do form submit that Checkboxes values not pass to the controller.
I have a form submit like this,
#using(Html.BeginForm("Index","Employee",FormMethod.Get))
{
<b>Search by :</b>#Html.RadioButton("Searchby", "EmpName",true)<text>Name</text>
#Html.RadioButton("Searchby", "IsPermanant")<text>Id</text><br />
#Html.TextBox("Search");
<input type="submit" value="Search" />
}
I have a controller
public ActionResult Index(string Search, bool Searchby)//In here searchby is null
{
}
Your creating a radio button group that will post back either the value "EmpName" or "IsPermanant", yet you are trying to bind it to a boolean property.
Either change the parameter bool Searchby to string Searchby or change the radio buttons to return true or false
You probably need to use the FormMethod.Post instead of FormMethod.Get
#using(Html.BeginForm("Index","Employee",FormMethod.Post))
{
<b>Search by :</b>#Html.RadioButton("Searchby", "EmpName",true)<text>Name</text>
#Html.RadioButton("Searchby", "IsPermanant")<text>Id</text><br />
#Html.TextBox("Search");
<input type="submit" value="Search" />
}
The second parameter of method RadioButton is value you want to pass to your controller. In your example you are passing EmpName or IsPermanant as string but your controller is expecting boolean. Changing the controller to accept string would allow you to pass the values you have for radio buttons.
public ActionResult Index(string Search, string Searchby)
{
}
i want to change grid date when the user change drop down values with ajax.
this is my C# code:
public ActionResult Index(string name)
{
ViewBag.Drop = db.Students.Select(r => r.Fname);
var model = from r in db.Students
where r.Fname == name
select r;
return View(model);
}
and this is cshtml file:
#using (Ajax.BeginForm("Index", new AjaxOptions
{
UpdateTargetId = "grid",
HttpMethod = "GET"
}
))
{
#Html.DropDownList("name", new SelectList(ViewBag.Drop));
<input type = "submit" value = "submit" />
}
<div id= "grid">
</div>
my problem is that when i change drop down values all of views are shown again. i don't want to see new view , just want to change grid data. how can i do that?
Do you have an action method which returns only the Grid data ? if not, create one
public ActionResult GridData(string name)
{
var gridItems=repo.GetCustomers(name).ToList();
//the above method can be replaced by your
// actual method which returns the data for grid
return View(model);
}
I am simply assumuing you have a Customer model with properties called FirstName and LastName and you want to show a list of Customers in the Grid. You may replace those with your actual class names and properties.
Make sure you have a view called GridData.cshtml which will render the HTML markup for your Grid
#model IEnumerable<YourNameSpace.Customer>
#{
Layout=null;
}
<table>
#foreach(var item in Model)
{
<tr><td>item.FirstName</td><td>item.LastName</td></td>
}
I would write simple (and clean) code like below instead of using Ajax.BeginForm
#Html.DropDownList("name", new SelectList(ViewBag.Drop));
<div id= "grid"></grid>
<script type="text/javascript">
$(function(){
$("select[name='name']").change(function(){
var url="#Url.Action("GridData","YourControllerName")"+"?name="+$(this).val();
$("#grid").load(url);
});
});
</script>
I have a dropdownlist that is being populated by a sql server, I am using Visual Studio 2010, cshtml, with razor as well as using the MVC pattern to create this project. What I am trying to do is when someone selects a value from the dropdown list on change it will update the page with information about that book.
I need help with the three things below:
user selects a book from the dropdownlist how to get the Book Name back to the controller
The server (retrieve the information from the server about the book) and
Back to view to be displayed.
I started with getting the dropdown poplulated.
My View looks like this
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
My Controller:
public ActionResult Index()
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
return View();
}
A dropdown list can't cause the page to post back to your controller on its own. You need to do one of two things:
Add a submit button so that the user changes the dropdown and then clicks a button to view the results.
Use javascript to submit the form on the element's change event.
Either way, you will need to wrap the dropdown/submit button in a form.
Option 1
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Option 2
<script type="text/javascript">
// assuming you're using jQuery
$(function() {
$('#UserSelectedValue').change(function() {
$(this).parent('form').submit();
});
});
</script>
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Your controller code would then become something like:
public ActionResult Index(string bookName)
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
if (!string.IsNullOrWhiteSpace(bookName))
{
ViewData["Books"] = _context.BookName.Where(b => b.Book_Name == bookName).ToList();
}
return View();
}