ActionLink routeValue from a TextBox - asp.net

I'm working on the following:
1- The user enters a value inside a textBox.
2- then clicks edit to go to the edit view.
This is my code:
<%= Html.TextBox("Name") %>
<%: Html.ActionLink("Edit", "Edit")%>
The problem is I can't figure out how to take the value from the textBox and pass it to the ActionLink, can you help me?

You can't unless you use javascript. A better way to achieve this would be to use a form instead of an ActionLink:
<% using (Html.BeginForm("Edit", "SomeController")) { %>
<%= Html.TextBox("Name") %>
<input type="submit" value="Edit" />
<% } %>
which will automatically send the value entered by the user in the textbox to the controller action:
[HttpPost]
public ActionResult Edit(string name)
{
...
}
And if you wanted to use an ActionLink here's how you could setup a javascript function which will send the value:
<%= Html.TextBox("Name") %>
<%= Html.ActionLink("Edit", "Edit", null, new { id = "edit" })%>
and then:
$(function() {
$('#edit').click(function() {
var name = $('#Name').val();
this.href = this.href + '?name=' + encodeURIComponent(name);
});
});

Related

Use textbox value on submit as a query string variable

How would I take a text box value and use it in the query string on submit? I'd like it to start as this,
/News?favorites=True
and end up something like this after the user enters in a search and clicks search.
/News?query=test&favorites=True
The controller action looks like this
public ActionResult Index(string query,bool favorites)
{
//search code
}
This question is something close to what I'd like to do, but I'd like to use the query string and maintain the existing values in the query string.
Thanks.
Two possibilities:
place the textbox inside a <form> with method="GET"
use javascript to read the value and pass it to the server (with AJAX or window.location to perform a redirect)
Example with a <form>:
<% using (Html.BeginForm("index", "news", FormMethod.Get)) { %>
<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<input type="submit" value="Search" />
<% } %>
Example with javascript:
<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<%= Html.ActionLink("Search", "index", "news", new { id = "search" }) %>
and then in a separate js file:
$(function() {
$('#search').click(function() {
var query = $('#query').val();
// Here you could use AJAX instead of window.location if you wish
window.location = this.href + '?query=' + encodeURIComponent(query);
return false;
});
});
Using Darin's above <form> answer but with Razor markup:
#using (Html.BeginForm("index", "news", FormMethod.Get))
{
<label for="query">Search:</label>
#Html.TextBox("query")
<input type="submit" value="Search" />
}

Simple ASP.NET MVC 2 Question - Using the Edit Scaffold

Good Morning,
I am using the editing scaffold. Here is the two bits of code:
Controller Code:
public ActionResult Edit(int id)
{
var viewModel = new ListingManagerViewModel
{
Listing = AfvClassifiedsDB.Listings.Single(l => l.ListingID == id),
Categories = AfvClassifiedsDB.Categories.ToList(),
};
return View(viewModel);
}
//
// POST: /ListingManager/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var listing = AfvClassifiedsDB.Listings.Single(l => l.ListingID == id);
try
{
// Save the changes to Listing.
UpdateModel(listing, "Listings");
AfvClassifiedsDB.SaveChanges();
return RedirectToAction("Index");
}
catch
{
// An error has occured so redisplay the form instead.
var viewModel = new ListingManagerViewModel
{
Listing = listing,
Categories = AfvClassifiedsDB.Categories.ToList(),
};
return View(viewModel);
}
}
View Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AfvClassifieds.ViewModels.ListingManagerViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<%: Html.EditorFor(model => Model.Listing, new { Categories = Model.Categories })%>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
This seems to work, but when you submit the form, the values aren't changed. This has been created using the MVC Music Store as a guide. No errors, but the form values I create aren't submitted.
Can you post the UpdateModel method?
However, it is clearly that you don't update anything there. You didn't do anything to the form collection FormCollection collection. the FormCollection is the actual form data that is inserted by user, so you should take all the values from it and save it in db.

Passing the value of a Textboxfor into ActionLink

Having a little trouble and wondered if anyone could help :-)
I am trying to pass the value that a user enters into a html.Textboxfor to an html.Action link.
As shown below :
<%=Html.TextBoxFor(m => m.OrderQty)%>
<p class="button" >
<%: Html.ActionLink("Add to cart",
"AddToCart",
"ShoppingCart",
new { id = Model.Product.ProductId, Qty = Model.OrderQty }, "")%>
</p>
But when i put a breakpoint in the AddToCart Qty is always 0 :-(
Does anyone have any ideas ?
Thanks
John
I would recommend you using a form instead of an action link. This way the value entered in the textbox will be automatically sent to the server and you don't have to worry about javascript:
<% using (Html.BeginForm("AddToCart", "ShoppingCart",
new { id = Model.Product.ProductId, Qty = Model.OrderQty },
FormMethod.Get)) { %>
<%= Html.TextBoxFor(m => m.OrderQty) %>
<input type="submit" value="Add to cart" />
<% } %>

How to return Nested PartialViews (including their javascript) from an AJAX call in ASP.Net MVC

I have created a treeview of Categories using nested partial views:
my Index page (that displays the treeview):
<div>
Category Menu:
<input type="button" value="1" name='selectCat_btn' />
<input type="button" value="2" name='selectCat_btn' />
</div>
<!-- Treeview -->
<% Html.RenderPartial("ItemCats_UL", Model); %>
<div id="CatSelectorOutput">
</div>
ItemCats_UL:
<div>
<ul id="catsTree">
<% Html.RenderPartial("ItemCats_LI", Model); %>
</ul>
</div>
<script type="text/javascript" >
$(document).ready(function() {
$("#catsTree").treeview();
</script>
ItemCats_LI:
<%foreach (ItemCategory itemCat in Model)
{ %>
<li>
<%= itemCat.Name %>
<%if (itemCat.Children != null && itemCat.Children.Count() > 0)
{ %>
<ul>
<% Html.RenderPartial("ItemCats_LI", itemCat.Children); %>
</ul>
<%} %>
</li>
<%} %>
Now this treeview works perfectly when I return the basic View("Index", Model) from my controllers Index action on page load.
The trouble comes when I want to change the Categories Model displayed in my Treeview (the nested partialViews) from an AJAX call...
For example: I click one the 'Cats2' button and the page should display Categories with ParentID of 2 in the Treeview. I attempted this by returning a JsonResult of the html of the ItemCats_UL PartialView (using a RenderPartialToString method found here) from my Controller Action. As some of you might know Javascript won't run in your partial view when you use an AJAX form to return a PartialViewResult, and I need Javascript in my Treeview which is why I'm using the RenderPartialToString.
The category select button click handler:
<script type="text/javascript">
$("[name='selectCat_btn']").click(function() {
var CID = $(this).attr('value');
$.ajax({
type: "POST",
url: "SelectCat",
dataType: "json",
data: { "CID": CID },
success: function(result) { $("#CatSelectorOutput").html(result.output); }
});
return false;
});
</script>
My Controller Action:
[AcceptVerbs(HttpVerbs.Post)]
[UrlRoute(Name = "SelectCat", Path = "selectCat")]
public ActionResult SelectCat(int CID)
{
IQueryable<ItemCategory> cats;
cats = ItemRepo.GetItemCats().WithCID(CID);
JsonResult result = null;
result = new JsonResult
{
Data = new
{
success = true,
output =
Helpers.RenderHelper
.RenderPartialToString("~/Views/Admin/AdminItemCatsUL.ascx",
cats)
}
};
return result;
}
The result:
The ItemCats_UL partialView displays! BUT the nested PartialViews (ItemCats_LI) don't!
Error I receive when I step through the markup in the ItemCats_UL.ascx and hover over the 'Html' part of the following code:
<ul id="catsTree">
<% Html.RenderPartial("ItemCats_LI", Model); %>
</ul>
Value cannot be null.
Parameter name: viewContext
Html = 'Html' threw an exception of type 'System.ArgumentNullException'
I'm wondering if there's a clever guy out there who can extend the RenderPartialToString method to include nested partialviews? Or am I missing something simple?
You need to hook the newly returned HTML / JavaScript back into the DOM upon loading it.
I'm sure there are lots of ways to do this, but I found a nice jQuery add-on called LiveQuery (link)
that helps me do it.
To make it work in your case, you'd set up a jQuery document.ready function in the parent page that looks something like this:
$("#catsTree").livequery(function () { this.treeview(); }, function () { /* code to destroy the treeview here */ });

Validating dynamically created fields in ASP.NET MVC

I have the following form in an ASP.NET MVC view:
<%= Html.ValidationSummary() %>
<% var fields = ViewData.Model; %>
<% using (Html.BeginForm("Dynamic", "Candidate")) { %>
<% foreach (var field in fields) { %>
<label for="<%= field.FieldName %>"><%= field.FieldName %></label>
<%= Html.TextBox(field.FieldName, field.Value, new { #class = "short" }) %>
<% } %>
<a class="button green" onclick="$('form').submit(); return false;">Submit</a>
<% } %>
I have a single controller action that loads this form as well as accepts the post, it looks like this:
public ActionResult Dynamic() {
var fields = DataProvider.Candidates.GetAllDynamicFields();
if (Request.HttpMethod == "POST") {
fields.ForEach(f => f.Value = Request[f.FieldName]);
var validation = DataProvider.Candidates.SaveDynamicFields(fields);
if (validation.IsValid)
return RedirectToAction("Index");
ViewData.ModelState.AddErrorsFromValidationResult(validation);
}
return View(fields);
}
My problem is that if any of the validators fail (i.e. the validation object contains errors) then I get an error on view rendering because ViewData.ModelState doesn't contain any keys. Where am I going wrong here? Any clues?
Figured it out. ViewData.ModelState is populated by the params in the response object. So with a dynamically created form you don't know exactly what was passed in the post. So I just recreate my ModelState on the fly:
fields.ForEach(f => ViewData.ModelState.Add(f.FieldName ...
And then we're all good...when the validation is run on the view it can find all the keys in the ModelState and no exceptions...works like a charm.
Asp.Net C# MVC Dynamic Forms (Changing Dom structure and getting data on the server)

Resources