I wonder if anybody can help me here. I apologise for sounding like a thicko but I'm new to MVC3 and I'm trying to pass 2 values from a view to an action method but it just isn't playing fair!
HTML:
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id }, new { htmlDataTemplateId = 1 })
ACTION METHOD:
public ActionResult AssignTokenToDataTemplate(int htmlTokenId, int htmlDataTemplateId)
{
// Do some database stuff here
return View("AssignAnExistingTokenToHtmlDataTemplate", new {templateId = htmlDataTemplateId});
}
I want to pass two integers into the AssignTokenToDataTemplate action method but I cannot get it to work?!
Can anybody see where I'm going wrong? :(
Try
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id , htmlDataTemplateId = 1 })
However you might want to consider using a model (a type of your own) to pass them together as one.
You could pass both values using the routeValues parameter:
#Html.ActionLink(
"ASSIGN", // linkText
"AssignTokenToDataTemplate", // actionName
"HostHtmlTokenManager", // controllerName
new { // routeValues
htmlTokenId = item.Id,
htmlDataTemplateId = 1
},
null // htmlAttributes
)
You have to include both parameters in the anonymous class:
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
null, new { htmlDataTemplateId = 1, htmlTokenId = item.Id })
Try;
#Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager",
new { htmlTokenId = item.Id, htmlDataTemplateId = 1 })
Matt
Related
Now i am using Kendo for Autocomplete text. Database is Northwind. But it always return undefined. I don't know to have any wrong thing?
View
#(Html.Kendo().AutoComplete()
.Name("cbRegion")
.Filter("contains")
.DataTextField("RegionDescription"))
.DataSource(s => { s.Read(r => r.Action("GetSupplier", "AutoComplete")).ServerFiltering(true); })
Controler
public JsonResult GetSupplier() {
var md = db.Regions.ToList();
List<RegionInfo> ls = new List<RegionInfo>();
foreach (var item in md) {
ls.Add(new RegionInfo{ RegionDescription = item.RegionDescription , RegionID = item.RegionID});
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var json = ser.Serialize(ls);
return Json(JArray.Parse(json), JsonRequestBehavior.AllowGet);
}
Image error
Please give me advise. Thanks
I am working on action result which returns JSON data to view and then loads on textFields by AJAX call
Action:
public ActionResult loadInf(string custm)
{
int smclientbranchid = Convert.ToInt32(Session["smclientbranchid"]);
var query = (from parent in db.Customer
join child in db.CustomerAddress on parent.CustomerId equals child.CustomerId
where parent.SMClientBranchId == smclientbranchid && parent.NIC == custm
select new SalesVM
{
Indicator = parent.Indicator,
//code removed
}).ToList();
return Json(query);
}
In View:
#Html.DropDownListFor(model => model.Indicator,
new SelectList(Enum.GetValues(typeof(ColorTypes))),
"<Select>",
new { #class = "form-control", id ="Indicator" })
<script type="text/javascript">
$(document).ready(function () {
$("#btnSearchCus").click(function () {
var custm = $('#custm').val();
$.ajax({
cashe: 'false',
type: "POST",
data: { "custm": custm },
url: '#Url.Action("LoadCustomerInfo", "Sales")',
dataType: 'json', // add this line
"success": function (data) {
if (data != null) {
var vdata = data;
$("#Indicator").val(vdata[0].Indicator);
//code removed
}
}
});
});
});
</script>
I am getting data right and also loading right except the "Indicator" field, which is of type enum.
How can I select an enum list item from the data I get.
For example:
0,1,2,3 index order
You need to be setting the Value attributes against all of the option values for the select list.
Use the following for your dropdown box to select by the text representation of the value:
#Html.DropDownListFor(model => model.Indicator, Enum.GetValues(typeof(ColorTypes)).Cast<ColorTypes>().Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString() }), new { #class = "form-control", id = "Indicator" })
Or use the following for it to select by the integer value:
#Html.DropDownListFor(model => model.Indicator, Enum.GetValues(typeof(ColorTypes)).Cast<ColorTypes>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }), new { #class = "form-control", id = "Indicator" })
This will allow your .Val() jQuery code to select the correct one.
If you retrieving string variable nm (0,1,2,3...) - would be better to change the type to int and try cast your integer variable to Enum type that you have.
public ActionResult loadInf(int nm)
{
ColorTypes enumValue = (ColorTypes) nm;
.......
You can take a look about details to this article: http://www.jarloo.com/convert-an-int-or-string-to-an-enum/
I want my Ajax.ActionLink to pass a viewModel property to action.
Here is my ViewModel
public class ViewModel
{
public string Searchtext { get; set; }
}
My .cshtml
#Ajax.ActionLink("Bottom3", "Bottom3",new { name = Model.Searchtext}, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "pointsDiv"
})
using(Html.BeginForm("Bottom3", "Home", FormMethod.Get))
{
#Html.TextBoxFor(x => x.Searchtext)
<button type="submit">Search</button>
}
<div id="pointsDiv"></div>
}
My Controller action:
public PartialViewResult Bottom3(string name)
{
var model = db.XLBDataPoints.OrderBy(x => x.DataPointID).Take(3).ToList();
return PartialView("Partial1", model);
}
But the name parameter passed to the action is always null. How do I solve this?
In your code... you have 2 different ways of posting to the server: the link and the form button.
The problem is that the ActionLink has no way to get the value from the input in client side... just the original value.
If you press the Search button, you will see a value posted.
Now, you can use some jQuery to modify a standard ActionLink (not the Ajax.ActionLink):
https://stackoverflow.com/a/1148468/7720
Or... you can transform your Form in order to do a Ajax post instead of a normal one:
https://stackoverflow.com/a/9051612/7720
I did this for a model of mine like so. I ONLY supported the HttpPost method. So add the HttpMethod="POST" to your Ajax.ActionLink
[HttpPost]
public ActionResult Accounts(ParametricAccountsModel model)
{
if (model.Accounts == null)
{
GetAccountsForModel(model);
}
if (model.AccountIds == null)
{
model.AccountIds = new List<int>();
}
return View(model);
}
On the razor view
#Ajax.ActionLink(
"Add Account to Order", "Accounts", "Parametric", null,
new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "...", HttpMethod = "POST" },
new { #id = "AddParametricAccountLink" })
The model has a list of selected account ids. So in javascript, I modified the href of the action link dynamically.
function UpdateParametricAccountAction() {
var originalLink = '/TradeNCashMgmt/Parametric/Accounts';
var append = '';
var numberOfRows = $('#ParametricAccounts').find('.parametric-account- row').size();
for (var i = 0; i < numberOfRows; i++) {
if (i != 0) {
append += '&';
}
else {
append = '?';
}
var idValue = $('#NotionalTransactionsAccountId_' + i).val();
append += 'AccountIds%5B' + i + '%5D=' + idValue;
}
$('#AddParametricAccountLink').attr('href', originalLink + append);
}
Since the model binder looks for parameter names in the query string and form submission, it will pick up values using the href. So I posted a model object using the querystring on my Ajax.ActionLink. Not the cleanest method, but it works.
I have this action in my controller which is returning a View...
public ActionResult SaveTimeShift(...)
{
try
{
if (Request.IsAjaxRequest())
return PartialView(....);
return View(userRecord);
}
catch (Exception e)
{
return PartialView(...);
}
}
Then this the html code in my viewpage...
using (Ajax.BeginForm("SaveTimeShift", new { }, new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "recordList", InsertionMode = InsertionMode.Replace, Confirm = "Do you want to save the new time shift?", OnSuccess = "partialRequestSuccess(data)", OnFailure = "partialRequestFailure" }, new { #class = "form-inline" }))
{
Now on my partialRequestSuccess(data) function on my OnSuccess parameter of AjaxOptions...
function partialRequestSuccess(data) {
if (data == 1)
alert("New Time Shift has been saved.");
}
Now my problem here is .... Im trying to set a value of my "data" variable that will be set in my controller... I did some research about returning a Json object unfortunately I'm returning a View in my controller... For now my "data" variable has a garbage value...Is there a way of knowing from my client side if my saving of data in the database was a success or not... Thanks! :)
You could store the data in your model or ViewBag in the action method:
ViewBag.MyVariable = "myValue";
then use in in the JavaScript
var myVariable = #Html.Raw(Json.Encode(ViewBag.MyVariable))
Using the following code:
#Html.ActionLink("News", "Index", new { controller = "News", area = "" }, new { #class = "News" })
I'm getting an error so that when I'm on a particular news article, the link is generating as:
http://mywebsite/News/2011/12/2/my_slug
where the parameters match the page that I'm currently on. The also happens on other controllers matching the same url schema (imagine I have another controller called Presentations that matches the url scheme of News entirely). From the presentations pages, a link to news would include the presentations parameters which aren't valid input for the news controller. Make sense?
I have my routes defined as:
routes.MapRoute(
"News-Archive", // Route name
"News/Archive", // URL with parameters
new { controller = "News", action = "Archive" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
routes.MapRoute(
"News-Stub", // Route name
"News/{year}/{month}/{date}/{slug}", // URL with parameters
new { controller = "News", action = "Index" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
routes.MapRoute(
"News-ByDay", // Route name
"News/{year}/{month}/{day}", // URL with parameters
new { controller = "News", action = "Archive" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
routes.MapRoute(
"News-ByMonth", // Route name
"News/{year}/{month}", // URL with parameters
new { controller = "News", action = "Archive" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
routes.MapRoute(
"News-ByYear", // Route name
"News/{year}", // URL with parameters
new { controller = "News", action = "Archive" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
routes.MapRoute(
"News-Default", // Route name
"News", // URL with parameters
new { controller = "News", action = "Index" }, // Parameter defaults
new[] { "mywebsite.Controllers" }
);
Can someone please explain if the problem lies in my use of Html.ActionLink or my route definitions?
EDIT:
Changing the Actionlink to:
#Html.ActionLink("News", "Index", new { controller = "News", area = "", year = string.Empty, month = string.Empty, day = string.Empty, slug = string.Empty}, null)
results in this when called from a presentation page (those values are for the presentation, not a valid news item):
http://mywebsite/News?year=2011&month=12&slug=seo_overview
Not sure why that's causing the rewriting to change.
The action link assumes the current slug since no slug was provided:
Use
ActionLink("News", "Index", new { controller = "News", area = "", slug="newslug"}, new { #class = "News" })
or
ActionLink("News", "Index", new { controller = "News", area = "", slug = null}, new { #class = "News" })
There is a chance that setting the slug = null would also re-use the current slug, in that case set the slug = Empty String.