This form searches for the value passed into "searchString" into a table and returns all the selected values.
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" />
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
}
This form is supposed to provide an "ActionLink" which will be clicked after a search is made and I want the action link to pass the previously searched string "searchString", when the link is clicked but it is sending an empty string.
<table class="table">
<tr>
<th>
#Html.ActionLink("Author", "Index", "Home", new { searchString = Html.Name("searchString").ToString()}, null)
</th>
</tr>
</table>
How do I retain the value of original search string "searchString" in this "ActionLink"? Both forms go to the same method Index().
function MyFunc()
{
if (($('#searchString').val()).length > 0) {
var url = "/Home/Index?SearchTerm=" + $('#searchString').val();
window.location.href = url;
}
else
{
alert('please enter value for search');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" id="searchString" />
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
<table class="table">
<tr>
<th>
<a href onclick="MyFunc()">Search</a>
</tr>
</table>
Please use this.
#Html.Action("Controller","actionName", new { searchString = "searchString" })
the other way is this
var searchString="abc";
#Html.Action("Controller","actionName", new { searchString = searchString })
You can send it by like variable through your controller :
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" value="#ViewBag.SearchString"/>
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
}
your controller should be like this
public ActionResult Search(string searchString)
{
ViewBag.SearchString = searchString; // This line send your string back to your view
return View();
}
for the link the same is applicable
<table class="table">
<tr>
<th>
#Html.ActionLink("Author", "Index", "Home", new { searchString = ViewBag.SearchString}, null)
</th>
</tr>
Related
I don't know why my "submit" button not responding. When I click on the edit button in each id, it can show a modal like this picture, so data is sent to the modal. But when I try to edit this data and click the button, it is not responding.
Here is my Index.cshtml
<div class="card-body">
<table id="datatablesSimple">
<thead>
<tr style="background-color:gray">
<th>No</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No</th>
<th>Name</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
#{ var stt = 1;}
#foreach (var item in ViewBag.List)
{
var itemName = "#exampleModalss" + item.id_category;
var itemName1 = "exampleModalss" + item.id_category;
<tr>
<td>#stt</td>
<td>#item.name</td>
<td>
<button type="button" class="btn btn-danger" data-bs-toggle="modal"
data-bs-target="#itemName">Edit</button>
</td>
</tr>
stt++;
<form action="/Category/edit" method="post">
<div class="modal fade" id="#itemName1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Category Book</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div id="resultss" class="modal-body">
<div class="row">
<div class="col">
<div class="">
<label for="category-film" class="col-form-label" style="font-weight:bold;width : 140px">Name Category: </label>
<input class="form-control" type="text" id="name" name="name" value=#item.name>
<input class="form-control" type="hidden" id="id_category" name="id_category" value=#item.id_category>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button style="width:100px" type="submit" class="btn btn-primary">Edit</button>
</div>
</div>
</div>
</div>
</form>
}
</tbody>
</table>
</div>
My Controller
[HttpPost]
public ActionResult edit(FormCollection form)
{
Category cat = new Category();
cat.id_category = Convert.ToInt32(form["id_category"]);
category.edit(cat);
return PartialView("Index", new { msg = "1" });
}
My DAO
public void edit(Category category)
{
var result = myDb.categories.SingleOrDefault(c => c.id_category == category.id_category);
result.name = category.name;
myDb.SaveChanges();
}
Here is my result when clicking on the Edit button with each id of the category book.
I get stuck in it few days, anyone can help me. I think
Edited for details
FormCollection is for list your form is just about a name and category id
then your model is not appropriate please change your model i mean create model class which contain name and category.
How would I do to when clicking the checkBox I call the action "ShowActives" of the controller?
This controller returns a list of elements that are active in the database.
How would I return these elements in the table?
my index is my default controller, clicking the checkBox I would like to call the ShowActives Action
public class CodigosDeOperacaoController : BaseController
{
public ActionResult Index()
{
return View(_codigosOperacionaisService.GetAll());
}
public ActionResult ShowActives ()
{
return View(_codigosOperacionaisService.GetActives());
}
}
My View
<div class="row">
<div class="col-md-12">
#using (Html.BeginForm("Index", "CodigosDeOperacao", FormMethod.Get))
{
<div class="row">
<div id="custom-search-input">
<div class="input-group col-md-12">
#Html.TextBox("buscar", null, new { #class = "form-control input", #placeholder = "Pesquisar por nome" })
<span class="input-group-btn">
<button class="btn btn-info btn" type="submit">
<big><i class="fa fa-search-plus"></i></big>
</button>
</span>
</div>
</div>
<div class="col-md-3 text-right">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Mostrar Todos</label>
</div>
<div class="col-md-6 text-right ">
<div>
<button type="button" id="btnNovo" class="btn btn-outline-primary btn-sm" style="min-width: 200px;">Novo código</button>
</div>
</div>
</div>
}
</div>
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Codigo)
</th>
<th>
#Html.DisplayNameFor(model => model.Descricao)
</th>
<th>Ações</th>
</tr>
#foreach (var item in Model)
{
if (!item.Ativo == false)
{
<tr style="background-color:aliceblue">
<td>
#Html.DisplayFor(modelItem => item.Codigo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descricao)
</td>
<td>
<a href="#Url.Action("Edit", "CodigosDeOperacao", new { id=item.Id })" class="btn btn-warning" style="margin-bottom: 3px" id="tamanho-botoes">
<span class="fa fa-edit"></span>
</a>|
<a href="#" class="btn btn-danger" style="margin-bottom: 3px" id="tamanho-botoes" onclick="iniciarExclusao('#item.Id')">
<span class="fa fa-ban"></span>
</a>
</td>
</table>
}
You can use Url.Action. Something like this should work:
<input type="checkbox" class="form-check-input" id="exampleCheck1"
onclick="location.href='<%: Url.Action("ShowActives", "CodigosDeOperacaoController") %>'" >
I have an ASP.NET MVC app. This app has a view that shows a list of records. I want to let my users add a record to this list. To do that, I've created a dialog that the user can enter information into. At this time, this dialog is a partial. I'm willing to change the implementation. I just need a dialog for adding. At this time, my views look like this:
Index.cshtml
<table class="table">
<thead>
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
<th>Email address</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Users)
{
<tr>
<td></td>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.Email</td>
</tr>
}
</tbody>
</table>
<br />
<button type="button" class="btn btn-default" onclick="addPerson()">Add Person</button>
#* Add Person dialog *#
<div id="addPersonModal" class="modal">
<div class="modal-dialog">
#{Html.RenderAction("Add", "Person");}
</div>
</div>
<script type="text/javascript">
function addPerson() {
$('#addPersonModal').modal('show');
}
</script>
Add.cshtml
#model MyApp.Models.AddPersonModel
#{ Layout = null; }
<div class="modal-content">
#using(Html.BeginForm("Add", "Person", FormMethod.Post))
{
<div class="modal-header">
<h4 class="modal-title">Add New Person</h4>
</div>
<div class="modal-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
<div class="col-md-6">
#Html.TextBoxFor(m => m.FirstName)
</div>
<div class="col-md-6">
#Html.TextBoxFor(m => m.LastName)
</div>
</div>
<div class="row">
<div class="col-md-12">
#Html.TextBoxFor(m => m.Email)
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Create</button>
</div>
#Html.AntiForgeryToken()
}
</div>
PersonController.cs
namespace MyApp.Controllers
{
public class PersonController : Controller
{
public ActionResult Index()
{
var model = new IndexModel();
return View(model);
}
public ActionResult Add()
{
var model = new AddPersonModel();
return View(model);
}
[HttpPost]
public ActionResult Add(AddPersonModel model)
{
if (ModelState.IsValid)
{
model.Save();
}
else
{
// I'm stuck here.
}
var listModel = new IndexModel();
return View("~/Views/Person/Index.cshtml", listModel );
}
}
}
Everything works except for validation. If the user enters some invalid data, the view reloads the entire screen and the data is lost. The dialog is also closed. I need to be able to show the values the user entered and the validation summary in the dialog window if the data is invalid. Yet, I'm not sure how to do this.
All,
I am trying to implement a ternary with a #using statement, in order to switch out the #enctype for certain cases, defined in my ternary. I am getting a Razor parse error stating that I am missing a closing "}" in my #using statement. This error is misleading because all of my curly braces match up fine. I am including the entire form since I cannot see any obvious issues with the syntax in the ternary section.
It looks like the issue is the if/else block but not sure why......
Any ideas why this is problematic? A better way?
#using(Ajax.BeginForm("ProcessCompose",
"ClubOpeningTool",
FormMethod.Post,
new AjaxOptions { UpdateTargetId = "update_panel" },
new { enctype = (fileAttachmentUnsupported ? "application/x-www-form-urlencoded" : "multipart/form-data"),
id = "ComposeForm" }))
{
#Html.ValidationSummary(true)
<fieldset style="width:90%">
<p class="required"><strong>* Required</strong></p>
<div id="update_panel"></div>
<div>
<span style="font-weight:bold; font-size:14px; color:#000000;">To:</span>
</div>
<div>
<table id="compose" class="table-grid">
<tr>
<td><strong>Available #(isTeam? "Team Mambers": Model.Mode)</strong> <br />
#Html.ListBox("AvaliableRecipients", Model.AvailabeRecipients, new{#class="ncb-listbox"})
</td>
<td><button id="addAllRecipient" type="button">>></button><br /><button id="addRecipient" type="button">> </button><br /><button id="removeRecipient" type="button">< </button><br /><button id="removeAllRecipient" type="button"><<</button>
<script type="text/javascript">
$(function () {
$('#addRecipient').click(function () {
$('#AvaliableRecipients option:selected').appendTo('#Recipients');
});
$('#addAllRecipient').click(function () {
$('#AvaliableRecipients option').appendTo('#Recipients');
$("#Recipients option").attr("selected", "selected");
});
$('#removeRecipient').click(function () {
$('#Recipients option:selected').appendTo('#AvaliableRecipients');
});
$('#removeAllRecipient').click(function () {
$('#Recipients option').appendTo('#AvaliableRecipients');
});
});
$("form").submit(function () {
$('#Recipients').find("option").attr('selected', 'true');
});
</script>
</td>
<td><strong>Current Recipients</strong> <span class="required">*</span><br />
#Html.ListBox("Recipients", Model.Recipients,new{#class="ncb-listbox"})<br /><span class="messageBottom">#Html.ValidationMessageFor(model => model.Recipients)</span>
</td>
</tr>
</table>
</div>
<div>
#Html.LabelFor(model => model.Subject) <span class="required">*</span>
</div>
<div>
#Html.EditorFor(model => model.Subject)<br />
<span class="messageBottom">#Html.ValidationMessageFor(model => model.Subject)</span>
</div>
#if (!fileAttachmentUnsupported)
{
<div>
<label>
File Attachment #Html.DisplayFor(model => model.FileName)
</label> <i>(9MB file size limit)</i>
</div>
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName">
#Html.TextBoxFor(model => model.FileAttachment, new {type = "file", #class = "js-file-field"})
<a class="btn blue js-file-btn">Browse</a>
}
else
{
<div>
<label>
<b>Attachment feature not available for Internet Explorer 10 (IE10 or earlier)</b>
</label>
</div>
}
#Html.HiddenFor(model => model.EmailID)
#Html.HiddenFor(model =>model.NewClubId)
#Html.HiddenFor(model =>model.Mode)
#Html.HiddenFor(m => m.DraftOrSentViewMode)
<div>
#Html.LabelFor(model => model.Body) <span class="required">*</span>
</div>
<div>
#Html.TextAreaFor(model => model.Body)<br />
<span class="messageBottom">#Html.ValidationMessageFor(model => model.Body)</span>
</div>
<p>
<input type="submit" id="btnComposeSend" name="Command" value="Send" class="btn blue saveSend"/>
#if (! isTeam) {
<input id="btnComposeSave" type="submit" name="Command" value="Save" class="btn blue saveSend"/>
}
</p>
</fieldset>
}
Not sure why this isn't working, maybe post the whole view? Having said that, if it was me, I would try this...
#using(Ajax.BeginForm(
"ProcessCompose",
"ClubOpeningTool",
FormMethod.Post,
new AjaxOptions { UpdateTargetId = "update_panel" },
new { #enctype = (fileAttachmentUnsupported ? "application/x-www-form-urlencoded" : "multipart/form-data"), id = "ComposeForm" }))
{ ... }
The problem was being caused by an unclosed input tag in the if/else block. Not sure why intellisense did not pick this up or why the error message was seemingly unrelated to the actual problem. Thanks everyone
Before
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName">
After
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName" />
I have an ASP.NET project and I have some checkbox to select the recurrence. I want to convert that to a string that will display it.
A simple version is
Create.cshtml
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<p style="font-weight:bold">New Record</p>
<div id="date">
<input type="checkbox" value="Sunday" />Sunday
<input type="checkbox" value="Monday" />Monday
<input type="checkbox" value="Tuesday" />Tuesday
...
</div>
<p>
<input type="submit" value="Create" />
</p>
<div align="left">
<font color="black" size="4" > #Html.ActionLink("<<Back to List", "Index", "Home", null, null)</font>
</div>
</fieldset>
}
And I want to save it in the model as a simple string like "1011011"
Standard Create function
[HttpPost]
public ActionResult Create(Event event)
{
if (ModelState.IsValid)
{
using (var context = new EventDBContext())
{
context.RecordList.Add(event);
context.SaveChanges();
}
return View("Index");
}
return View("Error");
}
What is the proper way to do this?
Utilize the CheckBoxFor Input extension
There are all sorts of walkthroughs on using them.