The issue i am facing has taken more then 8 hours but couldn't find the solution to it.
I am trying to implement ajax functionality in MVC4.
I've following code in index view.
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "resturantList"
}
))
{
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
}
<div id="resturantList">
#foreach (var item in Model)
{
<div>
<h4>#item.Name</h4>
<div>#item.City, #item.Country</div>
<div>Reviews: #item.CountOfReviews</div>
<hr />
</div>
}
</div>
Following is html which renders when search button is clicked.
I've checked the script files references by firebug even they are included
<script src="/Scripts/jquery-2.1.0.js">
<script src="/Scripts/jquery-ui-1.10.4.js">
<script src="/Scripts/jquery.unobtrusive-ajax.js">
<script src="/Scripts/jquery.validate.js">
<script src="/Scripts/jquery.validate.unobtrusive.js">
Tried to remove the
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
from web.config file which solves the above stated issue but it also disables the client side validations.
You are not telling the form to post the data on which action of which controller, this is causing the problem,do like this, pass controller and action name as well:
#using (Ajax.BeginForm(
"Action", "Controller",
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "resturantList"
}
))
{
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
}
<div id="resturantList">
#foreach (var item in Model)
{
<div>
<h4>#item.Name</h4>
<div>#item.City, #item.Country</div>
<div>Reviews: #item.CountOfReviews</div>
<hr />
</div>
}
</div>
and second thing,make sure you are returning a partial view,if full view is returing that will also cause issues.Do this in you view for it:
#{
Layout = null
}
Actually you have to return partial view in the response of ajax call
Related
I'm new to ASP.net MVC and I am struggling to make this work at the moment. I have a controller method called Add, it looks like this:
public ActionResult Add()
{
// check user is authenticated
if (Request.IsAuthenticated)
{
return View();
}
return RedirectToAction("Index", "Home");
}
//
// POST: /Home/Add
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(string title, string description, string priority, string color, FormCollection collection)
{
if (ModelState.IsValid)
{
// create instance of todo object
todo obj = new todo();
try
{
// gather fields
obj.priority = Convert.ToInt32(priority);
obj.color = Convert.ToInt32(color);
obj.title = title;
obj.description = description;
todosDataContext objLinq = new todosDataContext();
// get the users id, convert to string and store it
var userid = Membership.GetUser().ProviderUserKey;
obj.userid = userid.ToString();
// save
objLinq.todos.InsertOnSubmit(obj);
objLinq.SubmitChanges();
return RedirectToAction("Index", "Home");
}
catch
{
return View(obj);
}
}
return RedirectToAction("Index", "Home");
}
If data is sent via POST to the method, it should add the data to the database. That is working fine and everything is added correctly. However, the RedirectToAction is not firing, and the application gets stuck at /Home/Add, when it should redirect to /Home/Index. The view loads however, so it shows /Home/Index but the URL says /Home/Add.
Here is a copy of the partial view that contains the form:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<todo_moble_oauth.Models.todo>" %>
<% using (Html.BeginForm()) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<h3>Title:</h3>
<div class="editor-field">
<input type="text" name="title" />
</div>
<h3>Description:</h3>
<div class="editor-field">
<input type="text" name="description" />
</div>
<h3>Priority:</h3>
<div class="editor-field">
<select name="priority">
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<h3>Color:</h3>
<input type="radio" name="color" id="radio-choice-1" value="0" checked="checked" />
<label for="radio-choice-1">None</label>
<input type="radio" name="color" id="radio-choice-2" value="1" />
<label for="radio-choice-2">Red</label>
<input type="radio" name="color" id="radio-choice-3" value="2" />
<label for="radio-choice-3">Blue</label>
<input type="radio" name="color" id="radio-choice-4" value="3" />
<label for="radio-choice-4">Yellow</label>
</fieldset>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
So data is being sent to the database and stored, however the redirect is broken.
Turns out it is an issue with jQuery mobile, this threads solution resolved the issue for me:
jQuery Mobile/MVC: Getting the browser URL to change with RedirectToAction
I have a problem with using an ajax button in a partial view to update a div in the parent page. If I put the same button into the parent page it works fine. Is this not possible or am I missing something? cheers for the help
Parent View:
<div id="topiclist">
#{Html.RenderPartial("DetailLoader", this.Model);}
</div>
Partial View
#using (Ajax.BeginForm("LatestTopics", "Forums", new AjaxOptions { UpdateTargetId = "topiclist" }))
{
<input type="hidden" name="page" value="#ViewBag.page" />
<input type="submit" id="refresh" class="latestbuttons" value="#(ViewBag.NewTopics) New Topics" />
}
Include this line in your views, I had the same issue and it worked for me !
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Can any one pf you please tell me how to clear the File upload control value using javascript.
function ClearFileUpload()
{
var fil = document.getElementById("FileUpload1");
fil.select();
n=fil.createTextRange();
n.execCommand('delete');
fil.focus();
}
Due to security reasons there is no direct access to the value of a file upload control on the client using javascript.
What you could to is deleting the element out of the dom and recreating it. Have a look at this
link for an example
<div id="uploadFile_div">
<input type="file" id="uploadFile" onkeydown="return false;" size="40" name="uploadFile"/>
</div>
<a onclick="clearFileInputField('uploadFile_div')" href="javascript:noAction();">Clear</a>
<script>
function clearFileInputField(tagId)
{
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
}
</script>
working code tested IE,Firefox
<% using (Html.BeginForm("SaveSignatory", "LabMaster", FormMethod.Post, new { enctype = "multipart/form-data", id = "Signatory" }))
{ %>
<div>
</div>
<div id="divUpload">
<input type="file" name="filUpload" accept="image/*" id="filUpload" onchange="showimagepreview(this)" />
</div>
<img id="imgprvw" alt="uploaded image preview" height="200" width="200" />
<input type="button" id="btnRemoveUpload" value="Remove Upload Image" onclick="clearFileInputField('divUpload')" />
<input type="button" onclick="saveData()" />
<%}%>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML =
document.getElementById(tagId).innerHTML;
}
I have a route defined as:
routes.MapRoute("AllUsers",
"Users/Search/{Search}", new {
Controller = "Users", action=
"Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/", new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="search" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Currently as expected this creates a url of
../Users/Search/?search=searchTerm
but what I would like is:
../Users/Search/searchTerm
How is this possible? I thought of using javascript, but this seems a little dirty. Is there a more streamlined way of accomplishing this?
You cannot do that with an HTML form. Though you can mimic the behavior with JavaScript.
How about a server-side redirect?
You could do:
<input type="submit" id="submit" value="Search"
onclick="$('form').attr('action', $('form').attr('action') + $('#searchBox').val());" />
Which seems a little ugly. You could also not use a form and have this:
<input type="button" id="submit" value="Search"
onclick="window.location.href = 'search/' + $('#searchBox').val();" />
Outside of this, you could allow the original submit to go to the weird url, but use RedirectToAction in your controller.
Using jQuery you could something like this:
<script type="text/javascript">
$(function(){
$("#submit").click(function(){
document.location.href = $("form").attr("action") + $("#searchBox").val();
return false;
});
});
</script>
Try to change like this:
routes.MapRoute("AllUsers",
"Users/Search/{id}", new { Controller = "Users", action= "Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/",
new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="id" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Not tested, but "id" is default route value which are not creating "?name=value".
my first question here.. :)
Let's begin with the code...
my page is
<form id="form1" runat="server">
<% using (Ajax.BeginForm(null)){%>
<%=Html.DropDownList("DdlScelta",MVC.Models.SelectLists.ConventionIdsSelectList, "Select by this list")%>
<%=Ajax.ActionLink("Show the Data", "SetData", new AjaxOptions { UpdateTargetId = "msg" })%>
<span id="msg"></span>
</form>
and this is my controller method
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SetData(FormCollection form1)
{
//form1["DdlScelta"] etc
}
I've also tried with a better way like
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SetData(string DdlScelta)
{
//not important code
}
but NOTHING to do, as soon one of the 2 actionResult is catched, I have a null value..
Thank you to any who can help me :)
You have to submit the form
<input type="submit" value="Somevalue" />
and have the form like this
Ajax.BeginForm("actionName", "controllerName", ajaxOptions)
Something like this
<% using (Ajax.BeginForm("actionName", "controllerName", ajaxOptions))
{%>
//form stuff
<input type="submit" value="Somevalue" />
<% } %>