Search and display on same page in mvc2 asp net - asp.net-mvc

have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:

sathishkumar,
You don't tag the question as being an ajax related solution or not. I'm going to present a simple ajax approach which may or may not be suitable.
in the controller:
public ActionResult Search(string searchTerm)
{
// you don't add code re your stored proc, so here is a repo based approach
var searchItems = _repository.Find(x => x.searchfield.Contains(searchTerm));
return PartialView("SearchPartial", searchItems);
}
main view (index.aspx or whatever) (below where your main content is defined, add):
<div id="searchResults"></div>
in another part of the page (semi psuedo-code):
<script type="text/javascript">
function getSearchResults() {
// #yoursearchbox is a textbox on the index.aspx aview
var tdata = { searchTerm: $('#yoursearchbox').val()};
// or your data in the format that will be used ??
$.ajax({
type: "GET",
data: tdata,
url : '<%= Url.Action("Search", "Home") %>',
success: function (result) { success(result); }
});
});
function success(result){
$("#searchResults").html(result);
}
</script>
You'd then add a partial view SearchPartial.ascx that contained your model for the search results.
Hope this helps.

You can use Ajax to solve the problem.
<div>
`#using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
UpdateTargetId = "results",
HttpMethod = "GET",
}))
{
#Html.TextBox()
<input type="submit" value="Search" />
}`
<div id="results"></div>
</div>

Related

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

How to Pass textbox value using #html.actionlink in asp.net mvc 3

How to Pass value from text using #html.actionlink in asp.net mvc3 ?
None of the answers here really work. The accepted answer doesn't refresh the page as a normal action link would; the rest simply don't work at all or want you to abandon your question as stated and quit using ActionLink.
MVC3/4
You can use the htmlAttributes of the ActionLink method to do what you want:
Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })
MVC5
The following error has been reported, but I have not verified it:
A potentially dangerous Request.Path value was detected
Rather than passing your value using #Html.actionlink, try jquery to pass your textbox value to the controller as:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { search: $('#textboxid').val()},
success: function (result) {
$('#mydiv').html(result);
}
});
return false;
});
});
This code will post your textbox value to the controller and returns the output result which will be loaded in the div "mydiv".
to pass data from the client to the server you could use a html form:
#using (Html.BeginForm(actionName,controllerName)) {
<input type="text" name="myText"/>
<input type="submit" value="Check your value!">
}
be sure to catch your myText variable inside your controller's method
you can use this code (YourValue = TextBox.Text)
Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );
public class YourController : Controller
{
public ActionResult YourAction(int id)
{
return View("here your value", id);
}
}

Submit Data from partial view to a controller MVC

I have a list of employment records, you can also add an employment record from the same page using a partial view.
Heres employment.cshtml that has a partial view for the records list and a partial view to add a new record which appears in a modal pop up.
<h2>Employment Records</h2>
#{Html.RenderPartial("_employmentlist", Model);}
<p>
Add New Record
</p>
<div style="display:none">
<div id="regModal">
#{Html.RenderPartial("_AddEmployment", new ViewModelEmploymentRecord());}
</div>
</div>
Heres the partial view _AddEmployment.cshtml
#using (Html.BeginForm("AddEmployment, Application"))
{
#Html.ValidationSummary(true)
<div class="formEl_a">
<fieldset>
<legend></legend>
<div class="sepH_b">
<div class="editor-label">
#Html.LabelFor(model => model.employerName)
</div>
etc....etc....
</fieldset>
</div>
<p>
<input type="submit" class="btn btn_d" value="Add New Record" />
</p>
}
and heres my Application controller:
[HttpPost]
public ActionResult AddEmployment(ViewModelEmploymentRecord model)
{
try
{
if (ModelState.IsValid)
{
Add Data.....
}
}
catch
{
}
return View(model);
}
When compiling the following html is generated for the form:
<form action="/Application/Employment?Length=26" method="post">
It brings in a length string? and is invoking the Employment controller instead?
Hope all is clear....
QUESTION ONE: when I click the submit button from within the partial view it does not go to the controller specified to add the data. Can anyone see where im going wrong?
QUESTION TWO: When I get this working I would like to update the employment list with the new record....am I going about this the correct way? Any tips appreciated.
Answer 1: First try this and let me know if that hits your controller.
#using (Html.BeginForm("AddEmployment", "Application", FormMethod.Post))
Answer 2: To update the employment list, I would assume you would want to save the model to your database then have your employment list displayed on the same page or a different page calling the data from the DB into the the list or table to be displayed.
Edit:
It looks as though your form attributes are not being applied.
For your employment.cshtml, I personally don't use { } around my #Html statements.
You must not be doing what I stated above because your error occurs only when I write it as
#using (Html.BeginForm("AddEmployment, Application", FormMethod.Post))
missing those closing quotes is what is causing your problem.
jQuery code:
window.jQuery(document).ready(function () {
$('#btnsave').click(function () {
var frm = $("form");
var data = new FormData($("form")[0]);
debugger;
$.ajax({
url: '/Home/Update',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (response) {
alert(response);
},
error: function (er) { }
});
return false;
});
});
Controller Code
[HttpPost]
public JsonResult Update(Generation obj)
{
if (ModelState.IsValid)
{
return Json("done");
}
else
{
return Json("error create");
}
}
Using those code you can post form using jquery and get response in jsonresult
I know this is very old Question
the reason it didn't work for you because your syntax
Here is your code
#using (Html.BeginForm("AddEmployment, Application"))
the fix
#using (Html.BeginForm("AddEmployment", "Application"))
Regards
you have put #using (Html.BeginForm("AddEmployment, Application")) what this is trying to do is invoke a action called "AddEmployment, Application" i think you meant #using (Html.BeginForm("AddEmployment", "Application"))

Html.BeginForm not passing parameter

I have the following code that populates a Drop Down List and auto submits a form but it’s not passing the id back to the controller.
<script type="text/javascript">
$(function () {
$("#ArticleID").change(function () {
$('#TheForm').submit();
});
});
</script>
#using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" })){
#Html.DropDownList("ArticleID", (SelectList)ViewBag.ArticleId, "Select Article")
}
I get:
/Article/Details
But need:
/Article/Details/1
I’m following a tutorial that stops at this point. I’m not quite sure what is going on here regarding TheForm I tried to put ArticleID but that didn’t work. How do I do this?
I've also tried it without jQuery like this,
#using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" })){
#Html.DropDownList(
"ArticleID",
(SelectList)ViewData["Articles"],
"Please Select an Article",
new
{
onchange = "document.getElementById('TheForm').submit();"
})
}
But it doesn't send the parameter through either.
There is a built in way to render this without selecting the action:
var actionUrl = '#Url.Action("Details", "Article")/' + $('#ArticleID').val();
The url is determined before the page is rendered in the following line:
#using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" }))
which renders:
<form action="/Article/Details" id="TheForm" method="post">
Since the value that you want to add to the Url, ArticleID, is determined by the dropdown selection, you'll need to manipulate the action attribute of the form using JavaScript.
Something like this would probably work:
<script type="text/javascript">
$(function () {
$("#ArticleID").change(function () {
// The following line was changed to use #naspinski's suggestion
var actionUrl = '#Url.Action("Details", "Article")/' + $('#ArticleID').val();
$('#TheForm').attr('action', actionUrl);
$('#TheForm').submit();
});
});
</script>
With that said, this feel awkward to me. It may be worth considering how that value needs or will be used. Does it really need to be part of a route? If not, you can avoid this manipulating the action attribute altogether.

Invoking an action using jquery ajax

I am using ASP.NET MVC 2. I have a modal dialog (done through jquery UI) that contains two text boxes and a button. All the controls are inside a form.
I would like to invoke, when the user click the button, a controller action that do some operations on the passed data contained in the two text boxes and then return an integer value and a string message to the user.
Could anybody provide an example for doing this with jquery?
Thanks so much!
suppose you have the following form :
<form id="ajax-form">
<fieldset>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" value="send" />
</fieldset>
</form>
using jQuery
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.ajax({
type: "POST",
url: "Person/Add",
data: $("#ajax-form").serialize(),
success: function (response) {
// whatever you want to happen on success
},
error: function (response) {
alert('There was an error.');
}
});
});
});
Accessing Your Data in the Action Method.
public ActionResult Add(FormCollection form)
{
string firstname = form["firstname"];
string firstname = form["lastname"];
// do whatever you want here
// then return something to the view
return Json(/*some object*/);
}
another way is to use Microsoft Ajax
<% using (Ajax.BeginForm("Add", "Person",
new AjaxOptions() {
UpdateTargetId = "formDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })) {%>
<fieldset>
// Form Elements Here.
</fieldset>
<% } %>
UpdateTargetId is the id of the html element to be targeted.
The InsertionMode option has three values Replace, InsertAfter, InsertBefore
Hope that was helpful
Update : you don't have to return a Json result in your action method you can simply return a partial view or any HTML code as the response object and then insert it using jQuery.
You may take a look at the documentation about how you could implement a dialog that contains form fields. And when the confirm button is clicked you could simply send an AJAX request.
buttons: {
Confirm: function() {
// read the value in the textbox
var name = $('#name').val();
// send an AJAX request to an action that will return JSON:
$.getJSON('/home/foo', { name: name }, function(result) {
// read the returned value
alert(result.Value);
});
},
Cancel: function() {
$(this).dialog('close');
}
}
And your controller action:
public ActionResult Foo(string name)
{
return Json(new { Value = '123' }, JsonRequestBehavior.AllowGet);
}

Resources