Get Values of DropDownList which is inside webgrid and also each dropdown is an attribute of the model - asp.net-mvc

I have a webgrid contains a dropdown which contains different items for each user(Items are grouped). I want to get the selected values to the controller . How can I do that. Heres my ;
Model :
public SelectList AvailableDevices { get; set; }
View :
...
var grid = new WebGrid(Model. ...
..
..
grid.Column(header: "AvailableDevices", format: #item => Html.DropDownList("value", (IEnumerable<SelectListItem>)item.AvailableDevices)),
And I have a Submit Button
#using (Html.BeginForm("AssignUserDevices", "Device"))
{
<input type="submit" value="setUserDevice" onchange="CheckSelectedDevices()" />
}
I want to set users device according to his user type. I know what his choices and send dropdown items according to his type. So each item in webgrid differs from each other.
And Also I dont know how to give indices to each item in webgrid.( I think we will need it.)
Im new at MVC so hope you will understand.
Thanks;

What I got from our requirement that you want the selected item and have that item value in form field before posting if yes then you can follow as given.
#Html.DropDownList("value", (IEnumerable<selectlistitem>)item.AvailableDevices), new {#class="deviceclass"} )
#using (Html.BeginForm("AssignUserDevices", "Device"))
{
<input type="hidden" value="" name="deviceId" id="deviceId" />
<input type="hidden" value="" name="userId" />
<input type="submit" value="setUserDevice" />
}
<script>
$(".deviceclass").on('change', function () {
var dropdownvalue = $(this).val();
$('#deviceId').val(dropdownvalue);
})
</script>
and you can define an action function in controller
public ActionResult Details(string deviceId, string userId)
{
// do as you need.
return View();
}

Related

ASP Net Core - hidden input field data is not passed in the Controller

I need to pass which button is clicked for the form submit. But the hidden input is not received in the controller. Below are my code snippets
View Model:
public class DocumentViewModel
{
public int Id { get; set; }
public int ActionId { get; set; }
}
razor(cshtml):
<form....>
<input id="docActionId" name="docActionId" asp-for="ActionId" type="hidden" value="initialValue" />
</form>
JavaScript:
$("#save_btn").on("click", function ()
{
$("#docActionId").val("test1");
});
$("#submit_btn").on("click", function ()
{
$("#docActionId").val("test2");
});
I tried showing the current value in alert function if it is change and it did.
In my Controller/Action when I debug, I get a null value for the ActionId variable. I think this is very simple but I don't know what I did wrong.
Please help. I'm stucked in this for 2 hours now. Thanks in advance.
remove the "Id" attribute... that's all you need. "asp-for" does that. adding yours duplicates it kind
Remove the name="docActionId" html attributes, they will be generated automatically by Razor.
Specifically by the asp-for="ActionId" attribute.
Furthermore the reason this doesn't work is because the name attribute which is docActionId != ActionId which is the name of the property of your object. So it doesn't know where to bind it to.
<form id="myform">
<input id="docActionId" asp-for="ActionId" type="hidden" value="initialValue" />
<button type="submit" id="save">Submit</button>
</form>
Try this javascript perhaps the form is submitted before you attach the value
var saveButton = documnet.getElementById('save')
saveButton.addEventListener('click', function(e) {
e.stopPropagation();
documnet.getElementById('docActionId').value = "test value"
documnet.getElementById('myform').submit()
})
<input type="hidden" id="tag" >
type="hidden" didn't work for me with .net core 7 but only hidden keyword worked.
<input hidden id="tag">

How to render multiple checkboxs and radio buttons in view from database

i am new in mvc. the below is a sample of working with multiple check boxes and radio buttons but now i have to generate or inject in my page multiple multiple check boxes and radio buttons as per database. i have two master table called SEX and Hobbies. now i want to show as many as checkboxes as per the records for hobbies in db and the same way i want to show radio buttons for sex.
<form id='your-form' action='#Url.Action("Action","Controller")' method='post'>
<b>Gender</b><br />
<input type='radio' name='gender' value='Male' /> Male <br />
<input type='radio' name='gender' value='Female' /> Female <br />
<hr />
<b>Hobbies</b><br />
<input type='checkbox' name='hobbies' value='Reading' /> Reading <br />
<input type='checkbox' name='hobbies' value='Sports' /> Sports <br />
<input type='checkbox' name='hobbies' value='Movies' /> Movies <br />
<input type='submit' value='Update Profile' />
</form>
i do not know how to achieve it in mvc. do i need to iterate in view html or there is some other way to achieve it. i just want to work with check boxes not checkbox list or radio button list.
also like to know how to capture those value back when user click on submit button after selecting check boxes and radio buttons. if it is done by viewmodel then it would be great.
it will be great help if some one discuss with code sample just to better visualization purpose.
thanks
You need to use a ViewModel and then pass it back e.g.
View Model
public class ViewModel
{
public bool CheckBox1 { get; set; }
public bool CheckBox2 { get; set; }
}
Controller
public ActionResult Index()
{
var model = new ViewModel()
{
CheckBox1 = true,
CheckBox2 = false,
}
return View(model);
}
[HttpPost]
public ActionResult Action(ViewModel model)
{
// model will have your checkbox results
}
View
#model ViewModel
<form id='your-form' action='#Url.Action("Action","Controller")' method='post'>
<b>Gender</b><br />
#Html.RadioButtonFor(x => x.CheckBox1, "Male")
#Html.RadioButtonFor(x => x.CheckBox2, "Female")
<input type='submit' value='Update Profile' />
</form>
I would suggest you to create a model to your view and use Editor Templates.
In this case create a class which will hold the checkbox value and text for the check box say
class HobbyCheckBoxViewItem
{
public string Text {get;set;}
public bool IsChecked {get;set;}
public string HobbyID {get;set;}
}
Model for your main View
class SampleForm
{
public bool Gender {get;set; }
public List<HobbyCheckBoxViewItem> Hobbies {get;set; }
}
Now in your view use #Html.EditorFor(m=>m.Hobbies). For this your need to create EditorTemplates forlder in your view and create template for Hobbies List. Before that have look into EditorTemplates in MVC.
Populate your Hobbies List from the database.
When the user submits the form, your Hobbies List will be automatically populated based on the user selection. Don't forget to put hobby ID in the hidden field in your hobby editor template.
To achieve this easily, you will need a model backing up your view. Assume you have a model with two properties of List<Sex> and List<Hobbies>
This will be
#model Namespace.YourModel
#Html.BeginForm("Action","Controller",FormMethod.Post))
{
<b>Gender</b><br />
#for(int i = 0 ; i < Model.Sex.Count(); i ++)
{
#Html.RadioButton("gender",Model.Sex[i].Name) #Model.Sex[i].Name <br />
}
<hr />
<b>Hobbies</b><br />
#for(int i = 0 ; i < Model.Hobbies.Count();i++)
{
#Html.CheckBoxFor(x=>Hobbies[i].IsChecked) #Hobbies[i].Name
}
<input type='submit' value='Update Profile' />
}
This assumes that your Hobbies model has a 'Name', and IsChecked Property Property, change the name property to what ever your DB list uses,
This particular view Will post to any model that has
Properties of type List<Hobbies> and string Gender.

How To Pass Value Entered In A Text Box To An Action Method

I was building a Movies application using MVC. CRUD was automatically created for me by Visual Studio. Now, I am trying to build a Search functionality for the user. Here is the code I wrote:
#using (Html.BeginForm("SearchIndex", "Movies", new {searchString = ??? }))
{
<fieldset>
<legend>Search</legend>
<label>Title</label>
<input type ="text" id="srchTitle" />
<br /><br />
<input type ="submit" value="Search" />
</fieldset>
}
I have built the SearchIndex method and the associated view. I just can't find how to pass the value entered in the text box to the SearchIndex action method.
Please help.
In your Model:
public class Search
{
public String SearchText { get; set; }
}
Make your View strongly typed and use
#Html.EditorFor(model => model.SearchText)
In your Controller:
[HttpPost]
public ActionResult SearchIndex(Search model)
{
String text = model.SearchText;
}
Hope this helps.
You need to give your input field a name:
<input type="text" id="srchTitle" name="movieToFind" />
Then in your Controller make sure it has a string parameter:
in MoviesController:
[System.Web.Mvc.HttpPost]
public ActionResult SearchIndex(string movieToFind)
{
//Controller Action things.
}
Note: Form fields names must match the parameters expected in the controller. Or map to model properties if a 'Model' is expected.

MVC ERROR Illegal characters in path.

can someone tell me if im on the right track? Im trying to display my query but i get an error. I have two textbox with the same parameter and that parameter is declared as an IEnumerable.
[HttpPost]
public ActionResult Orders1(IEnumerable<int> order)
{
using (CostcoEntities1 context = new CostcoEntities1())
{
var query = string.Empty;
foreach (var orderID in order)
{
query = (from a in context.CM_Checkout_Details
where a.CheckoutDetails_ID == orderID
select a).ToString();
}
return View(query);
}
}
this is what my controller looks like..
I am trying to read the two numbers(Id) in the text box and diplay data based on those id.
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order")<br />
#Html.TextBox("order")
<input type="submit" value="Submit" />
}
First thing, change the names of the textboxes so that they are not the same:
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order1")<br />
#Html.TextBox("order2")
<input type="submit" value="Submit" />
}
Next, change the signature of your action method:
[HttpPost]
public ActionResult Orders1(string order1, string order2)
MVC's model binding will try to match order1 and order2 to stuff in Request.Form, for example, which should pick up the textbox values.

ViewData not being posted back to Controller

I have two pages, one that edits user information, and one that edits information in a pictures table. I recently stopped using strongly typed viewmodels due to the varying types of data required on each page.
The page that edits the user information works fine, but the page that edits picture information does not post back any of the edits that are made in the input fields; except for the ID, which is correct, all the other values come back as null. They both seem to be structured exactly the same way -- I can't figure out what's the difference. As far as I can tell the code for both pages are the same, but I'm not getting data back on the second one.
User Controller and View which works
Controller
public ActionResult Preferences()
{
int userid = getUserID(User.Identity.Name);
// Info for user preferences
var accountInfo = db.users.Single(l => l.ID == userid);
ViewData["accountInfo"] = accountInfo;
AccountController usr = new AccountController(); // Info for user menu
ViewData["userInfo"] = usr.getUserInfo(User.Identity.Name);
return View();
}
[HttpPost]
public ActionResult Preferences(user accountInfo, string oldPW)
{
// Do stuff to save user info
return RedirectToAction(actionname, routeValues);
}
View
#using (Html.BeginForm("Preferences", null, FormMethod.Post,
new { id = "prefsform" }))
{
AutoShowApp_MVC.user item = new AutoShowApp_MVC.user();
item = ViewBag.accountInfo;
<input id="lastname" name="lastname" type="text" value="#item.lastname"/>
<input id="address1" name="address1" type="text" value="#item.address1"/>
<input id="city" name="city" type="text" value="#item.city"/>
<input id="state" name="state" type="text" value="#item.state"/>
<input type="submit" value="Submit Changes" />
}
Picture Controller and View which DON'T work
Controller:
public ActionResult Edit(long id)
{
var picInfo = db.lmit_pics.Single(l => l.ID == id);
ViewData["picInfo"] = picInfo; // get Picture Info
// Get User Info for menu
AccountController usr = new AccountController();
ViewData["userInfo"] = usr.getUserInfo(User.Identity.Name);
return View();
}
[HttpPost]
public ActionResult Edit(lmit_pics picInfo)
{
// Do stuff to save picInfo
return RedirectToAction("Index");
}
View:
#using (Html.BeginForm("Edit", null, FormMethod.Post, new { id = "editform" }))
{
AutoShowApp_MVC.lmit_pics item = new AutoShowApp_MVC.lmit_pics();
item = ViewBag.picInfo;
<input type="text" id="model" value="#item.model" />
<input type="text" id="description" value="#item.description" />
<input type="submit" value="Save" />
}
You do not have the name attribute specified on the inputs on your picture editing form.
<input type="text" id="model" value="#item.model" />
Should Be
<input type="text" id="model" name="model" value="#item.model" />
The form collection works from the name attribute, not the Id attribute which is why you are not getting any data back (you are, it is just not properly attributed).
However, I agree with Wahid above, using strongly typed view models, editorFor helpers, etc not only help to prevent issues such as the above, but really go a long way in making a more secure, easier to maintain site.

Resources