I am very new to MVC and have Novice's knowledge about MVC.
I am creating an MVC application, where I have this page which displays Events taking place in a particular time.
Now when I select the event from the drop-down list, I get the specific event's details. Now along with that specific event's description, I need to get the feedback people has entered for that specific event.
Here is my View :
<div>Home >> Events</div>
<br />
<%:Html.LabelFor(m => m.Event)%>
<%:Html.DropDownListFor(m => m.Event.SelectedValue, Model.Event.GetSelectList(), new { id = "EventDropDown"})%>
<br /><br />
<div id="result" style="color: Green; border: 1px null transparent; ">
<%Html.RenderPartial("~/Views/PartialViews/EventsPartial.ascx"); %>
</div>
<%:Ajax.ActionLink("view", "viewFeedback", "Home", new AjaxOptions { UpdateTargetId = "comments" }, new {eventid=Model.Event.SelectedValue})%>
<div id="comments" style="color: Green; border: 1px null transparent;">
<%Html.RenderPartial("~/Views/PartialViews/FeedbackPartial.ascx"); %>
</div>
Can anyone please suggest how do I pass that event's ID in its ActionLink?
Thanks in advance
You can pass values with Html.ActionLink using routeValues in the parameter.
For example:
// VB
#Html.ActionLink("Link Text", "MyAction", New With {.eventId = 1})
// C#
#Html.ActionLink("Link Text", "MyAction", new {eventId = 1})
Might produce the link:
http://localhost/MyAction?eventId=1
u have to use ajax function for this:
$('youractionlinkid').click(function () {
var id = $('#yourdropdownid').val();
$.ajax({
url: this.href,
type: 'GET',
data: { id:id },
cache: false,
success: function (result) {
//do some action here
}
});
return false;
});
Razor will take AJAX this way also:
<div class="editorholder">
#Html.DropDownListFor(model => model.Display_ID, new SelectList(Model._listAllDisplayViewModel.ListAllDisplayInfo, "DisplayID", "DisplayName"), "Select.....", new { #class = "form-control", #id = "DisplayID", #onchange = "DisplayInfo();" })
</div>
<div class="editor-field">
<div id="DisplayView">
#Html.Partial("_DisplayView", Model._displayViewModel)
</div>
</div>
function DisplayInfo() {
$("#DisplayView").load('#(Url.Action("_DisplayView", "Display", null, Request.Url.Scheme))?id=' + $("#DisplayID").val());
};
Related
I have a MVC c#, signalR project where Agent follow below steps in Application
Login To application. Once login success application hides Login div panel & displays list of campaign & telephony buttons
Application displays list of campaigns agent is assigned to
Application displays button in front of each campaign to set Ready / Not Ready in campaign. In this case it is RestAPI & Telemarketing
If agent need to set himself not ready in campaign it opens popup window with list not ready reasons.
Issue is :
When Agent select reason and submit it application post back it lost view and reset to login window.
Controller action after submit of breakreason in PopUp window:
public ActionResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return RedirectToAction("Index");
}
PopUp Partial View :
#using Altitude.IntegrationServer.RestApiWebApp.Models
#model Altitude.IntegrationServer.RestApiWebApp.Models.breakReasonModel
<div id="divBreakReasons">
#using (Html.BeginForm("SetBreak", "Home"))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
</div>
Index.chtml
<div class="row">
<div class="col-md-4 table-responsive" id="telButtons">
<table id="tblTelephony" class="table">
--Telephony Buttons
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 table-responsive">
<p id="demo"></p> // Campaign table with Ready/Not Ready buttons
</div>
</div>
//ajax call to open popup
<div id="dialog" style="display: none"></div>
<script type="text/javascript">
function getBreak(nrReason) {
$("#dialog").dialog({
autoOpen: false,
modal: true,
});
$.ajax({
type: "POST",
url: "#Url.Action("popupBreak","Home")",
data: '{breakReason : "' + dataToSend + '",accessToken : "' +acc+ '",campaign : "' + cmp + '"}',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
console.log(response);
},
failure: function (response) {
},
error: function (response) {
}
});
}
</script>
It does exactly what you coded. If you need to return result to current view you should use ajax call that will return action result.
example
#using (Ajax.BeginForm("Action", "Controller", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "YourTargetForResult" }, new { #id = "ajaxForm" }))
You must reference jquery.unobtrusive-ajax.js to receive postback in current view.
Example based on your comment:
<input type="hidden" id="hdnResponseMessage" /> // add dom object where response hits
#using (Ajax.BeginForm("SetBreak", "YourControllerName", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "hdnResponseMessage" }, new { #id = "form" }))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
Conroller:
[HttpPost]
public JsonResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return Json("SetBreak");
}
jQuery set listener in document ready:
// add dom object listener
$('#hdnResponseMessage').bind('DOMNodeInserted', function () {
var txt = $('#hdnResponseMessage').text();
if (txt == 'SetBreak')
{
//do your stuff here;
}
});
I have a view which contains a list box. when users click on an item in the list box I have to post to a controller action method to see the value of the items selected/de-selected in the list box.
So it is posting to the controller action but the model is posted as null. When I post to the controller, I do serialize the form.
In other pages of my application when I serialize the form and post to the controller, the model is never null. I am not sure whats going on in this page but here is the code.
JS File
var serviceEntryURL = '#Url.Action("ServiceSystemSelection", "ServiceEntry")';
$('#systemlstbox').change(function () {
// alert('x');
var overlay = $('<div>loading errorcodes and parts..</div>').prependTo('body').attr('id', 'overlay');
$.post(serviceEntryURL,
$("#form").serialize(),
function (data) {
// $("#runDatestreeview").remove();
// $("#testExceptiontreeview").remove();
// $("#treeview").remove();
// $("#main").html(data);
// $("#ErrorCodeDisplay").empty();
}, "html");
overlay.remove();
});
View
#model RunLog.Domain.Entities.ServiceEntry
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm(new { id = "form", enctype = "multipart/form-data" }))
{
<fieldset>
<legend>Enter a new Service Log Entry</legend>
<h3>
</h3>
#Html.ValidationSummary(true)
<div class="exception">#(ViewBag.ErrorMessage)</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Service Request Number")
</span><span class="rightContent">[Generated] </span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Service Request Date / Time")
</span><span class="rightContent">
#Html.EditorFor(model => model.ServiceDateTime)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("Technician")
</span><span class="rightContent">
#Html.DropDownList("TechnicianID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
#Html.Label("System")
</span><span class="rightContent">
#Html.ListBoxFor(model => model.SelectedSystemIDs, new
MultiSelectList(ViewBag.SystemID, "Text", "Value",
Model.SelectedSystemIDs), new { id = "systemlstbox", name = "listbox" })
</span>
</div>
}
Controller Action
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ServiceSystemSelection(ServiceEntry serviceEntry)
{
}
I fixed it, the form serialization line was wrong.
$('#systemlstbox').change(function () {
// alert('x');
$.post(serviceEntryURL,
$('form').serialize(),
function (data) {
}, "html");
});
I am trying to get the model data from a strongly typed view to a controller.
Using the submit button is ok, I can get the data. Now I want to achieve the same with html.actionlink.
This is what I have:
View:
#model WordAutomation.Models.Document
#{
ViewBag.Title = "Document";
}
<script type="text/javascript">
$(function () {
$("#dialog").dialog();
});
</script>
<h2>Document</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Document</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ClientTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientTitle)
#Html.ValidationMessageFor(model => model.ClientTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientFullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientFullName)
#Html.ValidationMessageFor(model => model.ClientFullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientCustomSSN)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientCustomSSN)
#Html.ValidationMessageFor(model => model.ClientCustomSSN)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, new { id = "previewLink" })
</div>
<div id="dialogcontainer">
<div id="dialogcontent"><input type="submit" value="Create" /> </div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#dialogcontainer").dialog({
width: 400,
autoOpen:false,
resizable: false,
title: 'Test dialog',
open: function (event, ui) {
$("#dialogcontent").load("#Url.Action("PreviewWordDocument", "Home")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#previewLink").click(function(e) {
e.preventDefault();
$("#dialogcontainer").dialog('open');
});
});
</script>
}
Controller:
public ActionResult Document()
{
return View();
}
[HttpPost]
public ActionResult Document(WordAutomation.Models.Document model)
{
Models.Utility.EditWord word = new Models.Utility.EditWord();
word.EditWordDoc(model);
return View("Display", model);
}
public ActionResult PreviewWordDocument()
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
The document actionresult can get the model, but I want to know how can I get the values from the actionlink which will trigger the PreviewWordDocument action.
Thanks in advance, Laziale
The form can only be posted using the submit button to the URL given by its action attribute.
You can however send the form data to a different URL using the jQuery post method, manually validating the form before it is sent.
That way you can send the form data to the PreviewWordDocument controller method and handle the response in order to show the preview in the desired div.
(It will be helpful if you give an id to the form, so you can easily find it using jQuery)
So your click event handler for the preview link will look like this:
$("#previewLink").click(function(e) {
e.preventDefault();
if($("#YourFormId").valid()){
$("#dialogcontainer").dialog('open');
}
});
In the open function of the dialog you will post the form (which was already validated) to the preview controller method, using the jQuery ajax function. The response will be loaded into the dialogContent div:
$.ajax({
type: "POST",
url: $("#previewLink").attr("href"), //the preview controller method
data: $("#YourFormId").serialize(),
success: function (data) {
//load ajax response into the dialogContent div
$("#dialogcontent").html(data);
},
error: function(xhr, error) {
$("#YourFormId").prepend('<div id="ajaxErrors"></div>')
.html(xhr.responseText);
}
});
Now you will now be able to receive the whole document in the PreviewWordDocument action:
public ActionResult PreviewWordDocument(WordAutomation.Models.Document model)
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
in a HTML page when you click on a submit button all the input elements inside the form which the submit button resides in will posted to server, but when you click on a anchor (<a> tag ). you only send a request with a Get method and without posting any value.but if you want to send particular value to the server with this approach you can do it by query string.you have used following to make a request :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null,
new { id = "previewLink" })
this will produce :
<a id="previewLink" href="/Home/PreviewWordDocument"> Preview </a>
which is incorrect.to pass any value to the server with ActionLink use 4th parameter like this :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home",
new { id = "previewLink" }, null)
the result from this code would be :
Preview
cheers!
I am trying to pass a Form value "CustomerID" (i.e.dropdownlist selected value) using Ajax.Actionlink in MVC 4. Can someone tell me what I am doing wrong here?
<div class="editor-label">
#Html.LabelFor(model => model.CustomerID, "Customer Name")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.CustomerID, Model.CustomersList, "-- Select --")
#Html.ValidationMessageFor(model => model.CustomerID)
</div>
<div id="ApptsForSelectedDate">
#Ajax.ActionLink("Click here to view appointments",
"AppointmentsList",
new {id = Model.CustomerID},
new AjaxOptions
{
UpdateTargetId = "ApptsForSelectedDate",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "progress"
}
)
</div>
<div id="progress">
<img src="../../Images/ajax-loader.gif" alt="loader image" />
</div>
My controller method looks like this:
public PartialViewResult AppointmentsList(int id)
{ ... }
You should use an Ajax.BeginForm and put the dropdown inside the form. This way the value will be automatically passed.
Unfortunately since you cannot nest html forms if you already have another form wrapping this markup you cannot use a nested form.
In this case you could use a normal link:
#Html.ActionLink(
"Click here to view appointments",
"AppointmentsList",
null,
new { id = "applink" }
)
and in a separate javascript file AJAXify it and append the necessary information to the query string by reading the selected dropdown value at the moment the AJAX request is sent:
$(function() {
$('#applink').click(function() {
$('#progress').show();
$.ajax({
url: this.href,
type: 'GET',
data: { id: $('#CustomerID').val() },
complete: function() {
$('#progress').hide();
},
success: function(result) {
$('#ApptsForSelectedDate').html(result);
}
});
return false;
});
});
I want to show a confirmation dialog and if user press 'continue', the form will be submit.
This is the jquery code:
$(document).ready(function () {
$('#submit').click(function () {
$('#confirmation-dialog').dialog('open');
return false; // prevents the default behaviour
});
$('#confirmation-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$(this).dialog('close');
var form = $('transferForm', this);
$(form).submit();
return true;
},
"Cancel": function () {
$(this).dialog("close");
return false;
}
}
});
});
And this is the form:
#using (Ajax.BeginForm("Transfer", "Location", null, new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
//OnBegin = "ajaxValidate",
OnSuccess = "updateSuccess"
}, new { #id = "transferForm" }))
{
<div style="width:600px;">
<div class="editorLabel">
#Html.LabelFor(m => m.FromEmail)
</div>
<div class="editorText">
#Html.TextBoxFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="editorLabel">
#Html.LabelFor(m => m.ToEmail)
</div>
<div class="editorText">
#Html.TextBoxFor(m => m.ToEmail)
</div>
<div class="clear"></div>
<p>
<input type="submit" name="submit" value="Transfer" class="btn" id="submit"/>
</p>
</div>
}
<div id="update-message"></div>
<div id="commonMessage"></div>
<div id="confirmation-dialog">
<p>Are you sure you want to proceed with transfer ?
</p>
</div>
But after the confirmation, the form is not submitted.
What could be wrong here?? any ideas??
Try changing this:
var form = $('transferForm', this);
$(form).submit();
to:
$("#IDofForm").submit();
as this inside the dialogs event handlers probably does'nt refer to what you think it does, and you probably don't have an element with a transferForm tagname (which is what you're targeting when not using # or . in front of the selector) ?