I am using the microsoft ajax and the ajax form looks like this
<% using (Ajax.BeginForm("UserListing", new AjaxOptions
{
UpdateTargetId = "results",
OnComplete = "getData"
}))
{%>
<input id="Submit1" type="submit" value="submit" />
<%} %>
Now, i get the getData() js function called upon completion of the ajax request. all i want is that i need to access the response data of this ajax request inside this function and prevent that data being directed to the div with id results.
Thats because i am returning json result from the controller's action method and i need to parse it and display in the div.
script function is :
<script type="text/javascript">
function getData() {
alert("Response is : ");
}
</script>
the div tag is :
<div id="results">
</div>
I do not want to use other than microsoft ajax. kindly suggest me accordingly.
You could try rendering the response of the ajax request in a partial view containing only hidden fields. Then in your js function you can access the hidden fields using jQuery selectors.
So your action would look something like
[HttpPost]
public ActionResult UserListing()
{
List<string> data = GetUserListing();
return PartialView(data);
}
Your partial view will then only contain hidden fields that you render something like:
<% for (int i = 0; i < Model.Count(); i++)
{ %>
<input id="<%: "User" + i.ToString() %>" type="hidden" value="<%: Model[i] %>" />
<% } %>
That will render as:
<input id="User0" type="hidden" value="PeterSmith" />
Then in your javaScript function you can access each of the fields by doing something like:
function getData() {
var user = $('#User0').val();
alert(user);
}
That will show you the first field rendered. But you can enhance it a bit by looping through all the injected input fields.
Corrected this problem by myself as explained above. need some json parsers, currently looking for those..
Related
have been struggling with this. Tried everything I can think of. Im using javascript to pass data to db, works fine with ints on another page but now with strings it wont work :s
#using (Html.BeginForm(null, null, FormMethod.Post, new{#id="manageForm"}))
{
#Html.AntiForgeryToken()
<span class="actions">
#T(User.Id.ToString()) #T(" ") #T(ViewData["Tag"].ToString())
<input type="hidden" name="tag" value="fr" />
<input type="hidden" name="id" value="3" />
#T("Follow")
</span>
}
Javascript
<script type="text/javascript">
function followTag() {
$('#manageForm').attr('action', '#(Url.Action("FollowTag"))').submit();
return false;
}
</script>
Controller
[RequireAuthorization]
[HttpPost]
public ActionResult FollowTag(int id, string tag)
{
_service.FollowTag(id, tag);
return RedirectToAction("TagPage","Detail", new
{
});
}
Data Access
public void FollowTag(int id, string tag)
{
DbCommand comm = GetCommand("SPTagFollow");
//user id
comm.AddParameter<int>(this.Factory, "id", id);
//id to follow
comm.AddParameter<string>(this.Factory, "tag", tag);
comm.SafeExecuteNonQuery();
}
route is setup fine and sql(stored procedure) executes perfect. Hopefully one of you can see something obvious
cheers
I think is a problem of mistyping, check your last <a> tag, you typed following.() in the onclick event, see that your javascript function is called followTag.
If that doesn't fix it, then get rid of that foolowTag function, you can specify the action and the controller in the form itself, like this:
#using (Html.BeginForm("FollowTag", "YourControllerName", FormMethod.Post)) {
...
//Delete this line
//#T("Follow")
//This submit button will do the job
<input type='submit' value='#T("Follow")' />
}
That should do it. If you are using the anchor tag just for styling that's ok, otherwise you should use the other way, I think is clearer and besides it takes advantage of razor's great features.
I have a view that receives a Model and displays info of that model.
I have a submit button and when it is clicked i want it to send the id to the method to process it and delete a row that has such id.
How can I do this? I want to use a button not an html link like
#Html.ActionLink("Delete", "Delete", new { id = Model.Id }) |
Thanks!
I tried input type hidden but hasn't worked =(
You can use a form to do this... I don't use razor, but an equivalent .aspx way to do this would be:
<%using (Html.BeginForm("Home", "myaction", new { Id = 1 }))
{ %>
<input type="submit" value="submit" />
<%} %>
This will post to ~/Home/myaction/1
Just call Html.BeginForm with the appropriate razor syntax.
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" />
}
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 */ });
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)