<div id="newApplication" class="invisible">
<form id="frmnewApplication" action="">
<fieldset>
<ul class="formone">
<li>
<label class="labelone">
Name:</label>
<%-- <input type="text" id="ApplicationName" class="inputtext validate[required]" />--%>
<%= Html.DropDownList("ApplicationName", ViewData["AppList"] as IEnumerable<SelectListItem>)%>
</li>
This is my div. I am fetching the values from viewdata["AppList"]. My dropdown is fetching the values from ViewData in pageload only even though I am updating my viewdata in other controller methods it is not updating the viewdata. Plz help.
This is the jquery method
function updateDropdown() {
$("#ApplicationName").html("");
$.ajax({
type: "POST",
url: "/Shielding/AjaxGetDdlList",
dataType: "json",
success: function (data) {
if (data == null) {
alert("Something went wrong. Please try again;");
}
else {
for (group in data) {
var newOption = $("<option></option>").attr("value", data[group].ShieldFirewallApplicationId).html(data[group].ShieldFirewallApplicationName);
alert(data[group].ShieldFirewallApplicationName);
$("#ApplicationName").append(newOption);
}
}
}
});
}
This is the controller method:
public ActionResult AjaxGetDdlList()
{
return Json(ShieldingRep.GetAllApplications());
}
You may need to use tempdata. try to use viewmodels approach you may get help from this link
Viewdata isn't persisted between calls. The problem will be found in your controller.
Related
I'm looking for live search for ASP.NET and entity framework. I'm a little bit green with it. I read that it needs to use ajax, but I never used it before and can't get good example. Here is a piece of code, cshtml (part of textbox)
<div class="form-horizontal">
<hr />
<h4>Search for a client: </h4>
<div class="input-group">
<span class="input-group-addon" id="Name">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Name", "", new { #class = "form-control", placeholder = "Name" })
</div>
<div><h6></h6></div>
<div class="input-group">
<span class="input-group-addon" id="Surname">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Surname", "", new { #class = "form-control", placeholder = "Surname" })
</div>
<div><h6></h6></div>
<button type="submit" class="btn btn-default" data-toggle="modal" data-target="#infoModal">Search</button>
</div>
this is a part of controller:
public ActionResult Index(string Name, string Surname)
{
var SearchList = from m in db.Klienci
select m;
if (!String.IsNullOrEmpty(Name))
{
SearchList = SearchList.Where(s => s.Name.Contains(Name));
}
if (!String.IsNullOrEmpty(Surname))
{
SearchList = SearchList.Where(s => s.Nazwisko.Contains(Surname));
}
return View(SearchList);
}
So it search for me clients by name and surname, but it refresh full page when it lost focus or after clicking the button. How to solve it, to get live search? after each keystroke search through database? I'm a little bit green, would you Help me?
You can listen to the keyup event on your input element, read the value and send it to the server using ajax. Return the results and in the ajax call's success callback, update the ui with the results.
$(function() {
$("#Name,#SurName").keyup(function(e) {
var n = $("#Name").val();
var sn = $("#SurName").val();
$.get("/Home/Index?Name="+n+"&SurName="+sn,function(r){
//update ui with results
$("#resultsTable").html(r);
});
});
});
The code basically listens to the key up event on the two input textboxes and read the values and send to the /Home/Index action method using jquery get method asynchronously.When the action method returns the response, we update the DOM.
Assuming resultsTable is the Id of the table where we list the results.
Also, since you are returning the partial view result ( without layout headers), you should use return PartialView() instead of return View()
if(Request.IsAjaxRequest())
return PartialView(SearchList);
return View(SearchList);
Here is nice example/tutorial how to use Ajax with ASP.NET MVC
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
EDITED: 2016-07-20
Example:
$(function () {
$("searchField").keyup(function () {
$.ajax({
type: "POST",
url: "/Controller/Action",
data: data,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
You have to visit the server to get data from server and without ajax it is not possible. Now the question is how to make ajax call, you can use jQuery js lib to do but I would recommend you to try angular as data binding in angular will fulfill your needs.
Take a look at followings links
Angular Ajax Service -
jQuery Ajax
My partial view which is loaded into a bootstrap partial on my Index page, should be posting type Announcement but is posting type AnnouncementViewModel of the Index page model to the Create controller.
The #modal-container is specified in my _Layout, which is working as expected.
Unsure about the controllers - they appear correct, the problem is stemming from my ajax post I believe but I don't know what's the issue. I get the error after POST, however the database does update with the model correctly, but afterwards I get the below error.
I have specified $('#create-container')/$('form') as the form in which to serialize and send back to the controller.
Why is it doing this?
Error:
The model item passed into the dictionary is of type 'AnnouncementsViewModel', but this dictionary requires a model item of type 'Announcement'.
Index:
#model AnnouncementsViewModel
<h2>Announcements</h2>
<div>
#Html.ActionLink("Create", "Create", "Announcements", null, new { #class = "modal-link btn btn-sm" })
<div class="announcementTable">
<div id="announcementList">
#{Html.RenderPartial("List", Model.AnnouncementList);}
</div>
</div>
</div>
Partial:
#model Announcement
#section Scripts {
<script type="text/javascript">
$(function () {
$('#btn-create').click(function () {
$.ajax({
url: '#Url.Action("Create","Announcements")',
type: 'POST',
contentType: 'application/json',
data: $('#create-container').serialize(),
success: function (data) {
if (data.success == true) {
$('#modal-container').modal('hide');
location.reload(false)
} else {
$('#modal-container').html(data);
}
}
})
});
$('#btn-close').click(function () {
$('#modal-container').modal('hide');
});
});
</script>
}
<div class="create-container">
#using (Html.BeginForm())
{
<div class="newAnnouncementTableRow1">
<div>#Html.LabelFor(m => m.Title)</div>
<div>#Html.EditorFor(m => m.Title)</div>
<div>#Html.LabelFor(m => m.Details)</div>
<div>#Html.EditorFor(m => m.Details)</div>
</div>
<div class="newAnnouncementTableRow2">
<div>#Html.LabelFor(m => m.StartDT)</div>
<div>#Html.EditorFor(m => m.StartDT)</div>
<div>#Html.LabelFor(m => m.ExpiryDT)</div>
<div>#Html.EditorFor(m => m.ExpiryDT)</div>
<div>#Html.LabelFor(m => m.Enabled)</div>
<div>
#Html.RadioButtonFor(m => m.Enabled, 1)Yes
#Html.RadioButtonFor(m => m.Enabled, 0, new { #checked = "checked" })No
</div>
</div>
<div>
<button type="submit" id="btn-create" class="btn btn-sm">Save</button>
<button type="button" class="btn btn-default modal-close-btn" data-dissmiss="modal">Cancel</button>
</div>
}
</div>
Controller:
[HttpGet]
public ActionResult Index()
{
var avm = new AnnouncementsViewModel
{
AnnouncementList = new List<Announcement>()
};
avm.AnnouncementList = GetAnnouncementList();
return View(avm);
}
[HttpGet]
public ActionResult Create()
{
return PartialView("Create");
}
[HttpPost]
public ActionResult Create(Announcement a)
{
db.DbAnnouncement.Add(a);
db.SaveChanges();
return Index();
}
You set contentType: 'application/json' it your .ajax() call but returning View from Controller. Either change contentType to html or change controller to return JsonResult and return Json("yourData");
I recommend you to change your ajax call:
$.ajax({
/* other data */
dataType : "html",
contentType: "application/json; charset=utf-8",
/* other data */
success: function (data) {
$('#modal-container').modal('hide');
location.reload(false)
},
error: function (jqXHR, textStatus, errorThrown )
{
$('#modal-container').html(data);
}
/* other data */
});
Thing is response from server in your case always success but it returns html rather than json so you just don't have data.success at all.
The other issue as mentioned in the comments was that the controller was redirecting to an action method that it could not.
Changing return Index(); to return RedirectToAction("Index", "Announcements"); solved the error and the redirecting to the Create partial page caused by using return View();.
I have a very simple view and can't figure out why my textbox value is not passing to my controller. Will the actionlink work for providing the controller the parameter?
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("LookupEmployee", "Home")) {
<div class="jumbotron">
<h2>Personnel System</h2><br />
<p>ID: <input type="text" id=employeeID name="employeeID" /></p>
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null, new { #class = "btn btn-primary btn-large" })
</div>
}
<div class="row">
</div>
My HomeController takes the parameter and fills the dataset. I have hard coded a value and verified that this code works:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LeaveBalance(string employeeID)
{
//ViewBag.Message = "Your application description page.";
if (!String.IsNullOrEmpty(employeeID))
{
DataSet gotData;
LeaveRequestWCF myDataModel = new LeaveRequestWCF();
gotData = myDataModel.GetTheData(Convert.ToInt32(employeeID));
myDataModel.theModelSet = gotData;
return View(myDataModel);
}
return View();
}
}
Any advice? As you can tell, I'm new with MVC and trying to drift away from web forms.
OPTION 1:
You are using Html.ActionLink to post a form, which cannot be done because Html.ActionLinks are rendered as Anchor tags. Anchor tags make GET Requests unless we explicitly handle their JQuery click event. Use a Submit button to post a form for an appropriate controller action. So instead of -
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null,
new { #class = "btn btn-primary btn-large" })
go for -
<input type="submit" class="SomeClass" value="Submit" />
OPTION 2:
You can also use AJAX POST using JQuery click event for anchor tag to post the form and once you get the result, you can make a client side redirection.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#solTitle a").click(function() {
var data = {
"Id": $("#TextId").val()
};
$.ajax({
type: "POST",
url: "http://localhost:23133/api/values",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
// handle redirection here
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
ActionLink creates a simple <a href /> on the page, that will send a get request to the server.
You need a submit button instead, so your form gets posted with its form inputs. Use:
<button type="submit">Your Leave Balance</button>
I have action method like this:
[ChildActionOnly]
public ActionResult NewUserLanguage()
{
...
return View(model);
}
This view have one simple form on it and a list of partial views:
<ul id="userLanguagesListBox">
#foreach (var l in Model.UserLanguages)
{
<li>
#{Html.RenderPartial("UserLanguageBox", l);}
</li>
}
...
This partial view looks like this:
...
#using (Html.BeginForm("EditUserLanguage", "UserLanguage", FormMethod.Post, new { id = "editUserLanagegeForm" }))
{
<ul>
<li><h3>#Model.Language.Name</h3></li>
<li>#Model.LanguageLevel.Name</li>
<li>
#Html.HiddenFor(x=>x.UserLanguageId)
<button class="editButton">Edit</button>
</li>
</ul>
}
What I am trying to do is when user click on edit button in any of the partials I want to switch it with another view EditUserLanguage.
I have tried something like this:
$(function () {
$('#editUserLanagegeForm').submit(function (e) {
alert('ss');
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$("#" + e.target).closest("div").append(result);
}
});
return false;
});
});
But this function is never called by any of edit buttons.
"The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus."
-From http://api.jquery.com/submit/
What this means to you is that you need your button to have a type of submit for the submit event to trigger, but I don't think that's the one you're thinking of. Try using .click() instead.
I'm trying to return the generated HTML string to the view to dynamically generate a HTML table with results. I'm not able to get the returned HTML string any suggestions and help is greatly appreciated.
Here is my Controller code
public ActionResult ValidateTrams()
{
string html = "";
if (Request.Files.Count == 0 || Request.Files[0].ContentLength == 0)
{
}
else
{
html = ProcessTextFile(Request.Files[0].InputStream);
}
return View(html);
}
I'm trying to grab this returned result in jquery like this
$('#tramsView').live('click', function () {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'jsonp',
success: function (data) {
alert(data);
$('#TramsViewFrame').html(data);
},
error: function (jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) { window.location.reload(); }
}
});
});
Finally Below is the CSHTML for the form. Here I'm reading a file from a form with a button type submit
<form action="#" method="post" enctype="multipart/form-data" class="forms" name="form"
id="frmvalidate">
<table>
<tr>
<td>
<input type='file' name='trams' id='ValidatetramsFile' />
</td>
</tr>
<tr>
<td>
<br />
<input name="cbDisplayUmatched" id="cbDisplayUmatched" type="checkbox" value="" checked="true" />
<label style="text-decoration: none; outline: none; font-size: 1.1em; padding: 3px 0 0px 0;">
Display rows that were <strong>NOT</strong> parsed</label>
</td>
</tr>
<tr>
<td>
<br />
<div class="buttons">
<button type="submit" value="VIEW" class="ui-state-default ui-corner-all" id="tramsView">VIEW</button>
</div>
</td>
</tr>
</table>
</form>
Thanks for your time and really appreciate your help. Kind Regards!!!
you can return HTML from action like this,
return Content(html, "text/xml");
It sounds as if your form is still submitting a normal postback, so any asynchronous calls that you're doing are being lost.
Try preventing the default form submission taking place with the following:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
// ... rest of your code
});
Incidentally, in this case, if all you're doing is updating the html on your #TramsViewFrame, you could just use the slightly simpler $.load() method:
$('#tramsView').live('click', function (evt) {
evt.preventDefault();
$('#TramsViewFrame').load('/Booking/ValidateTrams');
});
Make these changes
Give the attribute HttpPost on top of your controller
[HttpPost]
public ActionResult ValidateTrams()
return the string as Json like this from the controller.
return Json(new { success = html });
Finally change your dataType from jsonp to json
$('#tramsView').live('click', function() {
$.ajax({
url: '/Booking/ValidateTrams',
type: 'POST',
dataType: 'json',
success: function(data) {
alert(data.success);
$('#TramsViewFrame').html(data.success);
},
error: function(jqxhr, textStatus, errorThrown) {
$(window).hideWaitScreen();
if (confirm(errorThrown)) {
window.location.reload();
}
}
});
});
P.S: If you are using the latest version of jQuery (1.7+), please change the .live handler to .on handler. Not mandatory :)
In your controller since you are using ajax post you need to return as JSON it would be something like this
return Json(html);
i think this is another way relevant to your scenario How can I return the HTML from MVC controller to a div in my view
http://mazharkaunain.blogspot.com/2011/02/how-to-use-aspnet-mvc-javascriptresult.html
instead of storing in "string" store html codes in following format:
HtmlString s = new HtmlString("<html coding/>");
ViewData["Id_as_per_your_choice"] = s;
return View("page_you_want to_respond");
then place "<%: ViewData["Id_Same_as_that_in_above_code"] %>" where ever you want that html code to appear......simple.....
but make initial value of Viewdata as null in "index()"method so that code doesnot appear on page load....