Multiple Search Buttons in MVC3 - asp.net-mvc

There are a few questions on SO about multiple submit buttons, such as How do you handle multiple submit buttons in ASP.NET MVC Framework? but what I am having trouble with is having multiple search buttons, each with it's own associated textbox for the value being searched for, and which searches it's own set of data. For example..
<div class="leftContentColumnRow">
#Html.TextBox("SearchString", null, new { placeholder = "Search Roles..." })
<input type="submit" value="" class="searchbtn" name="SearchRoles" />
</div>
<div class="rightContentColumnRow">
#Html.TextBox("SearchString", null, new { placeholder = "Search Permissions..." })
<input type="submit" value="" class="searchbtn" name="SearchPermissions" />
</div>
I can determine which button has been clicked, but I am struggling to get hold of the data in both textboxes.

Use a separate form for each input button pair with a different action for the form.

Like Oded said, 2 forms, each has it'w own action paramter value.
#using(Html.Beginform("SearchRole","User")
{
<div class="leftContentColumnRow">
#Html.TextBox("SearchString", null, new { placeholder = "Search Roles..." })
<input type="submit" value="" class="searchbtn" name="SearchRoles" />
</div>
}
#using(Html.Beginform("SearchPermissions","User")
{
<div class="rightContentColumnRow">
#Html.TextBox("SearchString", null, new { placeholder = "Search Permissions..." })
<input type="submit" value="" class="searchbtn" name="SearchPermissions" />
</div>
}
and the Action methods
public ActionResult SearchRole(string SearchString)
{
//get data and return something
}
public ActionResult SearchPermissions(string SearchString)
{
//get data and return something
}

Related

How do I pass CheckBox values from a view to a controller using #Html.CheckBox?

I need to display 6 types of tests on my view and allow the user to check as many tests as they'd like to complete. I will then need to send their response to my controller so I can add that information to a database using the entity framework.
my View:
#using (Html.BeginForm("Quote", "Customers", FormMethod.Post))
{
<label for="test1"> BP</label>
#Html.CheckBox("test1", true)<br />
<label for="test2"> DS</label>
#Html.CheckBox("test2")<br />
<label for="test3"> IS</label>
#Html.CheckBox("test3")<br />
<label for="test4" class="iput">PS</label>
#Html.CheckBox("test4")<br />
<label for="test5">PF</label>
#Html.CheckBox("test5")<br />
<label for="test6">CS</label>
#Html.CheckBox("test6")<br />
<input type="submit" value="Begin Quote" class="btn btn-default" style="padding-left: 20px" />
}
and my controller method:
[HttpPost]
public ActionResult Quote(FormCollection collection )
{
if (!string.IsNullOrEmpty(collection["test1"]))
{
string checkResp = collection["test1"];
bool checkRespB = Convert.ToBoolean(checkResp);
}
return View("Index");
}
I am running into an issue when debugging...The collection["test1"] is returning a "true, false" value instead of the actual checked value of the checkbox. I cannot seem to get the form to collect the actual statuses of the check boxes.
I have tried other options but none have seemed to work. Any help is greatly appreciated!

Data not populating in form upon clicking edit

I am working on this ASP.NET MVC project where I am performing simple CRUD operations. On clicking Edit button, I want to get the data from the database and populate it in the Create View (same view with the help of which I entered the data).
The issue that I have is that, though I am able to enter the data into the database using the Create.cshtml view, I am not able to populate the data back into the fields to the same View upon clicking Edit. On checking, I see that I am able to get the data from the database from the Controller and I am sending it to the View - Create. But, the fields are not getting populated in the View.
Where am I going wrong?
View - Create.cshtml
<form method="post" action="/Books/Create" id="formBooks">
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<div>
<label asp-for="Title" class="label">Title</label>
<input asp-for="Title" class="form-control" id="title" name="title" required />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div>
<label asp-for="Author" class="label">Author</label>
<input asp-for="Author" class="form-control" id="author" name="author" required />
<span asp-validation-for="Author" class="text-danger"></span>
</div>
...
</div>
<div class="form-group col-md-6">
<button type="submit" value="Save" class="btn bgm-orange waves-effect mybtn">SAVE</button>
</div>
</div>
</div>
</form>
Controller - BooksController.cs
public ActionResult Create(int? Id)
{
if(Id == null)
{
return View();
}
else
{
var bookData = _context.Books
.Where(b => b.ID == Id)
.FirstOrDefault();
return View(bookData);
}
}
public ActionResult Create(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Books books= db.Books.Find(id);
if (books== null)
{
return HttpNotFound();
}
return View(books);
}
//Try this i hope this will work
The name attribute plays a vital role in binding the data to the <input></input> field. Also, value attribute gets the value to display in the Edit view.
<input asp-for="Title" class="form-control" id="title" name="title" placeholder="Enter title..." value="#(Model != null ? Model.Title : "")" required />

MVC foreach set item.ID to model.ID

I have a form that shows all the available hotel rooms, each room has a button that does a HttpPost if clicked, I have made a property in the BookingViewModel called 'RoomID'. I would like to assign the item.RoomID to Model.RoomID so I can use it in my controller to get the id from the selected room but i'm not sure how to achieve this.
ChooseRoom View
#foreach (var item in Model.AvailableRooms)
{
<li class="room-item clearfix">
<h5>#item.Name</h5>
<div class="room-list-left">
<img src="#item.Image" alt="" />
</div>
<div class="room-list-right">
<div class="room-meta">
<ul>
<li><span>Occupancy:</span> #item.Adults Adults #item.Childs Children</li>
#if (item.SmokingRoom)
{
<li><span>Smoking Allowed:</span> Yes</li>
}
else
{
<li><span>Smoking Allowed:</span> No</li>
}
</ul>
</div>
<div class="room-price">
<p class="price">From: <span>$#item.Price</span> / Night</p>
</div>
<div class="clearboth"></div>
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input class="button2" type="submit" value="Select Room" />
}
BookingController
[HttpPost]
public ActionResult ChooseRoom(BookingViewModel vm)
{
BookingViewModel bookingObj = GetBooking();
bookingObj.SelectedRoom = Repository.GetRoomByID(vm.RoomID);
return View("reservation", bookingObj);
}
Thank you for your time!
update your begin form as below
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input type="hidden" name="RoomId" value="#item.RoomID" />
<input class="button2" type="submit" value="Select Room" />
}
Just need to provide input tags having the same name as your ViewModel property.
You could add inputs in foreach loop , it should be inside form. Something like this <input name="Model.AvailableRooms[index].RoomID" value="Id Here"/>
Or if you want to select one Room you should use ajax and post id.
If I'm not wrong you form is in loop,so you could add hidden input with id
#Html.HiddenFor(c => c.AvailableRooms[index].RoomID)

Submitting a form to ASP.NET MVC from Knockout does not bring in all the values

Here is what I have in my view in ASP.NET MVC 5
#model Entities.Coupon
#using (Html.BeginForm("coupon", "marketing", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="scsm-18 scmd-16 sclg-14">
<div class="form-group">
<label>Codes</label>
#Html.TextBoxFor(p => p.Code, new { #class = "form-control", #data_bind = "value: Code", #autofocus = true, #maxlength = "50" })
</div>
<input type="radio" name="IsPerCentOrDollar" value="1" data-bind="checked: IsPerCentOrDollar" />
<span>PercentageAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="2" data-bind="checked: IsPerCentOrDollar" />
<span>DollarAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="3" data-bind="checked: IsPerCentOrDollar" />
<span>FreeShipping</span>
</div>
<div class="panel-footer text-right">
<input type="submit" name="commandType" id="btnSave" class="btn btn-primary" data-bind="click:submit" value="Save" />
</div>
}
In the script:
$(document).ready(function () {
var viewModel = new CouponViewModel(couponModel);
ko.applyBindings(viewModel);
function CouponViewModel(data) {
self.Code = ko.observable(data.Code);
self.IsPerCentOrDollar = ko.observable("1");
self.DiscountLevel = ko.computed(function () {
return self.IsPerCentOrDollar();
});
};
}
Code in MVC:
[HttpPost, ActionName("coupon")]
public ActionResult coupon(Coupon coupon)
{
try
{
// some logic not yet in
}
catch (Exception ex)
{
}
return View();
}
That's all I have in there now.
In Developer tools inside the browser I can see values for self.DiscountLevel change on the selection of radio buttons.
On Submit, at MVC front the value of Code comes in but the values for DiscountLevel are not.
Any help is greatly appreciated.
Regards.
Let me expand on #StephenMuecke's comment (which has the gist of it I think).
ASP.NET MVC's default model binding will fill the argument (Coupon) with values found in the request. Only form elements are sent along with the request. You seem to expect that DiscountLevel is sent along, but it's just a JavaScript function that exists in the user's browser.
Adding something like this may solve your immediate problem:
<input type="hidden" name="DiscountLevel" data-bind="value: DiscountLevel" />
To note a related issue though: the property you have trouble with is a computed observable. However, you probably do not want to send it along as it depends entirely on IsPerCentOrDollar. Just have your server side Coupon class derive the discount level from that property too. That would also prevent users from hacking the hidden input and sending in a malicious value.

Pass constant value and variable (input) text from View to Controller

I'm fairly new to ASP.NET MVC and still getting used to some of the concepts.
I understand that to pass the value of a text box in the View back to the Controller, I can use Html.BeginForm and give the text box the same name as the corresponding parameter in the Controller Action.
Here's my situation: I have 2 buttons. I want them to call the same Action in the Controller. I want them to both pass the value for the text box (i.e. the "searchText").
However, I want one of the buttons to pass "false" for the parameter isQuickJump and I want the other button to pass "true" for the parameter isQuickJump.
Here is my View:
#using (Html.BeginForm("SearchResults", "Search", FormMethod.Get)) {
<div id="logo" class="centered">
<a href="SearchResults">
<img alt="Search" src="../../Content/themes/base/images/Search.jpg" />
</a>
</div>
<div id="searchBox" class="centered">
#Html.TextBox("searchText", null, new { #class = "searchTextBox" })
</div>
<div id="buttons" class="centered">
<input type="submit" id="searchButton" value="Search" class="inputBtn" />
#Html.ActionLink("Quick Jump", "SearchResults", "Search", new { isQuickJump = true }, new { #class = "btn" })
</div>
}
Controller:
public ActionResult SearchResults(string searchText, int? page, int? size, bool? isQuickJump, GridSortOptions sort)
{
var items = GetSearchGrid(searchText, page, size, sort);
if (Request.IsAjaxRequest())
return PartialView("_SearchResultsGrid", items);
return View(items);
}
Any suggestions on how to do this?
I appreciate your help!
Just use 2 submit buttons with the same name and different value:
<div id="buttons" class="centered">
<button type="submit" name="isQuickJump" value="false">Search</button>
<button type="submit" name="isQuickJump" value="true">Quick Jump</button>
</div>
Depending on which button is clicked the corresponding value will be sent to the server for the isQuickJump parameter. And since both are submit buttons, they will also submit all other input fields data to the server (which was not the case with the anchor that you used as the second button).

Resources