Passing id of selected dropdown option to Controller - asp.net-mvc-3

I am using mvc3 nhibernate and creating a search application...
Here i am creating a dropdown list containing all Hobby names and on click of search button the selected option's id should go to post method
i have written following code in my controller
public ActionResult Details()
{
ViewBag.h=new SelectList(new Hobby_MasterService().GetHobbies(),"Hobby_Id");
return View();
}
[HttpPost]
public ActionResult Details(int Hobby_Id)
{
Hobby_Master hm = new Hobby_MasterService().GetHobby_Data(Hobby_Id);
return RedirectToAction("Show");
}
and in view i'm only showing one drop down list as
<b>Select Hobby:</b>
#using (Html.BeginForm("Details", "Hobbies", FormMethod.Get))
{
<div class="Editor-field">
#Html.DropDownListFor(Model => Model.Hobby_Id, (IEnumerable<SelectListItem>)ViewBag.h)
</div>
<input type="submit" value="Search" />
}
My dropdown is populated through a function which has a normal sql statement...
and i can generate list....but how will i get the selected hobbies id...
Please help

maybe FormMethod.Post on your form?
and is your Model a class?
Perhaps you could accept that in your post action then you'll find the id on it.

without bothering with model binding, you can just add a FormCollection parameter to your POST method. That collection contains all form values posted.
[HttpPost]
public ActionResult Details(FormCollection collection)
{
Hobby_Master hm = new Hobby_MasterService().GetHobby_Data(Hobby_Id);
if (collection["Hobby_Id"] != null)
{
// collection["Hobby_Id"] contains the value selected in the dropdown box
}
return RedirectToAction("Show");
}

Related

Using submit and text to pass a value to a controller

I am a begginer with asp.net mvc 3. I want to create a page where an user can enter a search item and retrieve the data from database. I have created the database. I have created the controller which is:
public ActionResult SearchIndex(string id)
{
string searchString=id;
var search = from m in db.Searches
select m;
if (!String.IsNullOrEmpty(searchString))
{
search = search.Where(s => s.Name.Contains(searchString));
}
return View(search);
}
I want to pass the value from view page to the above controller. What should be the code in view page to enter an item to search from above mentioned controller?
So create your view with a form inside... something like this:
#using (Html.BeginForm())
{
<label>Search:</label>
<input type="text" name="searchString" />
<input type="submit" name="submit" />
}
Then in your controller you can use the FormCollection object to grab your searchString like this:
[HttpPost]
public ActionResult SearchIndex(FormCollection formCollection)
{
string searchString = formCollection["searchString"];
...
}

MVC3/Razor to Controller Ajax call

I have a Razor view with a couple of dropdown lists. If the value of one of the dropdown's is changed I want to clear the values in the other drop down and put new ones in. What values I put in depends on the values in the model that the view uses and that is why I need to send the model back from the view to the controller. The controller will then also need to be able to modify the dropdown by sending back data to the view. Note, that I am not saying that I want to go back to the controller from a form submit using Ajax. I am going back to the controller using a form submit, but not using Ajax.
Please can someone give me some simple code or some pointers to show how this might be done.
Thanks
I personally use ViewBag & ViewData to solve this condition.
Controller:
public ActionResult Index()
{
ViewBag.dd1value = default_value;
ViewBag.dd1 = DropDownlist1();
ViewBag.dd2 = DropDownlist2(dd1value);
Return View();
}
View:
In the first dropdownlist add an onchange javascript.
<select onchange="javascript:this.form.submit();">
#foreach (var item in ViewBag.dd1) {
if (ViewBag.dd1value = item.dd1value)
{
<option selected value="#item.dd1value">#item.dd1text</option>
}
else
{
<option value="#item.dd1value">#item.dd1text</option>
}
}
Then, on submit button give it a name.
<input type="submit" name="Genereate" value="Generate" />
In the controller, create 2 ActionResult to receive data.
For dropdownlist:
[HttpPost]
public ActionResult Index(int dd1value)
{
ViewBag.dd1value = dd1value;
ViewBag.dd1 = DropDownlist1();
ViewBag.dd2 = DropDownlist2(dd1value);
Return View();
}
For submit button:
[HttpPost]
public ActionResult Index(int dd1value, int dd2value, FormCollection collection)
{
ViewBag.dd1value = dd1value;
ViewBag.dd2value = dd2value;
ViewBag.dd1 = DropDownlist1();
ViewBag.dd2 = DropDownlist2(dd1value);
ViewBag.result = Result(dd1value, dd2value);
Return View();
}
If you don't need button:
[HttpPost]
public ActionResult Index(int dd1value, int dd2value)
{
ViewBag.dd1value = dd1value;
ViewBag.dd2value = dd2value;
ViewBag.dd1 = DropDownlist1();
ViewBag.dd2 = DropDownlist2(dd1value);
ViewBag.result = Result(dd1value, dd2value);
Return View();
}
Please note that if you use ViewBag / ViewData, all the help you get from the compiler is disabled and runtime errors/bugs will occur more likely than if the property has been on a "normal" object and typos would be catched by the compiler.
I would implement a different solution from DragonZelda.
I would create a ViewModel object containing the data that you need on the page, that the View binds to.
Then, I would create controls that bind to that Model, like:
#Html.DropDownListFor(x => x.SomeDDLSelected, ......)
x.SomeDDLSelected would be a property in your ViewModel object that would automatically get the selected value in the dropdownlist when the automatic model binder gets in action.
Then, to finalize it, the Controller action would receive your ViewModel object as a parameter:
public ActionResult MyAction(MyViewModelObject obj)
{...}
And you get all your data nice and tidy, all strong typing.

MVC3 Razor "For" model - contents duplicated

It has been intriguing that my MVC3 razor form renders duplicated values inside a foreach code block in spite of correctly receiving the data from the server. Here is my simple form in MVC3 Razor...
-- sample of my .cshtml page
#model List<Category>
#using (#Html.BeginForm("Save", "Categories", FormMethod.Post))
{
foreach (Category cat in Model)
{
<span>Test: #cat.CategoryName</span>
<span>Actual: #Html.TextBoxFor(model => cat.CategoryName)</span>
#Html.HiddenFor(model => cat.ID)
<p>---</p>
}
<input type="submit" value="Save" name="btnSaveCategory" id="btnSaveCategory" />
}
My controller action looks something like this -
[HttpPost]
public ActionResult Save(ViewModel.CategoryForm cat)
{
... save the data based on posted "cat" values (I correctly receive them here)
List<Category> cL = ... populate category list here
return View(cL);
}
The save action above returns the model with correct data.
After submitting the form above, I expect to see values for categories similar to the following upon completing the action...
Test: Category1, Actual:Category1
Test: Category2, Actual:Category2
Test: Category3, Actual:Category3
Test: Category4, Actual:Category4
However #Html.TextBoxFor duplicates the first value from the list. After posting the form, I see the response something like below. The "Actual" values are repeated even though I get the correct data from the server.
Test: Category1, Actual:Category1
Test: Category2, Actual:Category1
Test: Category3, Actual:Category1
Test: Category4, Actual:Category1
What am I doing wrong? Any help will be appreciated.
The helper methods like TextBoxFor are meant to be used with a ViewModel that represent the single object, not a collection of objects.
A normal use would be:
#Html.TextBoxFor(c => c.Name)
Where c gets mapped, inside the method, to ViewData.Model.
You are doing something different:
#Html.TextBoxFor(c => iterationItem.Name)
The method internall will still try to use the ViewData.Model as base object for the rendering, but you intend to use it on the iteration item. That syntax, while valid for the compiler, nets you this problem.
A workaround is to make a partial view that operates on a single item: inside that view you can use html helpers with correct syntax (first sample), and then call it inside the foreach, passing the iteration item as parameter. That should work correctly.
A better way to do this would be to use EditorTemplates.
In your form you would do this:
#model List<Category>
#using (#Html.BeginForm("Save", "Categories", FormMethod.Post))
{
#Html.EditorForModel()
<input type="submit" value="Save" name="btnSaveCategory" id="btnSaveCategory" />
}
Then, you would create a folder called EditorTemplates, either in the ~/Views/Shared folder or in your Controllers View folder (depending on whether you want to share the template with the whole app or just this controller), and in the EditorTemplates folder, create a Category.cshtml file which looks like this:
#model Category
<span>Test: #Model.CategoryName</span>
<span>Actual: #Html.TextBoxFor(model => model.CategoryName)</span>
#Html.HiddenFor(model => model.ID)
<p>---</p>
MVC will automatically iterate over the collection and call your template for each item in it.
I've noticed that using foreach loops within Views causes the name attributes of text boxes to be rendered the same for every item in the collection. For your example, every text box will be rendered with the following ID and Name attributes:
<input id="cat_CategoryName" name="cat.CategoryName" value="Category1" type="text">
When your controller receives the form data collection, it won't be able reconstruct the collection as different values.
The solution
A good pattern I've adopted is to bind your View to the same class you want to post back. In the example, model is being bound to List<Category> but the controller Save method receives a model ViewModel.CategoryForm. I would make them both the same.
Use a for loop instead of a foreach. The name/id attributes will be unique and the model binder will be able to distinguish the values.
My final code:
View
#model CategoryForm
#using TestMvc3.Models
#using (#Html.BeginForm("Save", "Categories", FormMethod.Post))
{
for (int i = 0; i < Model.Categories.Count; i++)
{
<span>Test: #Model.Categories[i].CategoryName</span>
<span>Actual: #Html.TextBoxFor(model => Model.Categories[i].CategoryName)</span>
#Html.HiddenFor(model => Model.Categories[i].ID)
<p>---</p>
}
<input type="submit" value="Save" name="btnSaveCategory" id="btnSaveCategory" />
}
Controller
public ActionResult Index()
{
// create the view model with some test data
CategoryForm form = new CategoryForm()
{
Categories = new List<Category>()
};
form.Categories.Add(new Category() { ID = 1, CategoryName = "Category1" });
form.Categories.Add(new Category() { ID = 2, CategoryName = "Category2" });
form.Categories.Add(new Category() { ID = 3, CategoryName = "Category3" });
form.Categories.Add(new Category() { ID = 4, CategoryName = "Category4" });
// pass the CategoryForm view model
return View(form);
}
[HttpPost]
public ActionResult Save(CategoryForm cat)
{
// the view model will now have the correct categories
List<Category> cl = new List<Category>(cat.Categories);
return View("Index", cat);
}

how can i transfer information of one view to another?

i have designed a view in asp .net mvc3 off course registration form. This is very simple form having name ,father name , qualification and a submit button , after pressing submit button i want to display information by using another view. please suggest me how can i send information from one view to another view.
my controller class is :
namespace RegistrationForm.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// ViewBag.Message = "Welcome to ASP.NET MVC!";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
return View();
}
}
}
my view is :
#{
Layout = null;
}
registrationView
Enter Name
</td>
<tr>
<td>
Enter Father Name
</td>
<td>
<input type="text" name="fname" id="fname" />
</td>
<tr>
<td>
Enter Qualification
</td>
<td>
<input type="text" name="qly" id="qly" />
</td>
</tr>
</table>
<input type="submit" value="submit" />
</div>
well, we faced this problem before, and the best way to get this to work was to define a model that this page will work with, then use this model object when posting back, or redirecting to another view.
for your case, you can simply define this model in your Models folder
ex: RegistrationModel.cs file, and define your required properties inside.
after doing so, you will need to do 2 more steps:
1- in your GET action method, create a new RegistrationModel object, and provide it to your view, so instead of:
return View();
you will need something like:
var registrationModel = new registrationModel();
return View(registrationModel);
2- Use this model as a parameter in your POST Action method, something like
[HttpPost]
public ActionResult registrationView(RegistrationModel model)
{
// your code goes here
}
but don't forget to modify the current view to make use of the provided model. a time-saver way would be to create a new dummy View, and use the pre-defined template "Create" to generate your View, MVC will generate the properties with everything hooked up. then copy the generated code into your desired view, and omit any unneeded code.
this is a Pseudo reply. if you need more code, let me know
<% using Html.Form("<ActionName>") { %>
// utilize this HtmlHelper action to redirect this form to a different Action other than controller that called it.
<% } %>
use ViewData to store the value.
just remember that it will only last per one trip so if you try to call it again, the value would have been cleared.
namespace RegistrationForm.Controllers { public class HomeController : Controller { public ActionResult Index() { // ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewData["myData"] = "hello world";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
// get back my data
string data = ViewData["myData"] != null ? ViewData["myData"].ToString() : "";
return View();
}
}
And you can actually usethe ViewData value on the html/aspx/ascx after redirect to the registrationView.
For example on the registrationView.aspx:
<div id="myDiv">
my data was: <%= ViewData["myData"] %>
</div>
You could simply in you method parameter list declare the parameters with the name of the controls. For example:
The control here has an id "qly"
<input type="text" name="qly" id="qly" />
Define your method parameter list as following:
public ActionResult YourMethod(string qly)
{
//simply pass your qly to another view using ViewData, TempData, or ViewBag, and use it in the desired view
}
You should use TempData which was made exactly for it, to persist values between actions.
This example is from MSDN (link above):
public ActionResult InsertCustomer(string firstName, string lastName)
{
// Check for input errors.
if (String.IsNullOrEmpty(firstName) ||
String.IsNullOrEmpty(lastName))
{
InsertError error = new InsertError();
error.ErrorMessage = "Both names are required.";
error.OriginalFirstName = firstName;
error.OriginalLastName = lastName;
TempData["error"] = error; // sending data to the other action
return RedirectToAction("NewCustomer");
}
// No errors
// ...
return View();
}
And to send data to the view you can use the model or the ViewBag.

how to store value in database selected in dropdown list

this is my action of controller class
public ActionResult checking()
{
rikuEntities db = new rikuEntities();
IEnumerable<SelectListItem> items = db.emp.Select(c => new SelectListItem
{
Value = c.name,
Text = c.name
});
ViewBag.saan = items;
return View();
}
Now i want to use this dropdownlist value in my UserCreate.cshtml.
when i select a value from dropdownlist values and press submit then that value should store in another table student.
please suggest me what should i do for it ?
First of all you need to define your form:
using (Html.BeginForm())
{
#HTML.DropDownList("SomeName", (SelectList)ViewBag.saan)
<input type="submit" value="save" />
}
Then in your post controller:
[HttpPost]
public ActionResult checking(string SomeName)
{
...
}

Resources