VS '12 asp.net C# mvc Internet App + Kendo UI , EF Code First, Kendo UI
Using Kendo DDL
#(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Leasehold A", "Mineral Owner", "Prospect", "StrangerInTitleNote", "StrangerInTitleNoteInfo", "StrangerLeasingNote", "StrangerLeasingNoteInfo", "Subject To", "Surface Note", "Surface Note Info", "Unreleased Mortage", "Unreleased Oil and Gas Leasors", "Vesting Note" })
)
Very simple right? - now i want to extract the selected Item and place it into an Actionlink
#Html.ActionLink("Create New", "Create", new { id = } )', null) ....
what do I place at the id= spot. How can I get this to work. Thanks for any answers.
PS: Not familiar with MVC to much or any HTML so far, must I use a Script? - preferably I would like to not leave the view.
I do it like this. May not be the best but it works for me.
Here is the link:
#Html.ActionLink("Click Me", "YourAction", new { controller = "YourController"}, new {id="YourActionLinkName"})
The .click function
$('#YourActionLinkName').click(function (e) {
var val = $("#dropdownlist").val();
var href = "/YourApp/YourController/YourAction/" + val;
this.href = ""; //clears out old href for reuse
this.href = href; //changes href value to currently slected dropdown value
});
Related
i have a website like this simple image
Everything in the redbox is the Index page with a default layout, the blue shows my partial view.
I have a mvc controller for emails, via a ajax actionlink i change the partial view. So you don't have to reload the complete page if you want to switch the folder.
Everything works fine if you go the follow way:
-Click on Email in the Navbar and you comes to the Index page from Email which opens a automatic the Inbox Partial view.
This is my code in the Html to call the Inbox Partial:
<div id="emailBody">
#Html.Action("EmailPartial", new { module = "1", id = "1,2" })
</div>
The Partial Controller has the follow code:
public PartialViewResult EmailPartial(string module, string id = "1,2", int start = 0, int anzahl = 100)
{
if (module == "1")
{
List<Emailstatus> emailStati;
List<int> TagIds = id.Split(',').Select(int.Parse).ToList();
emailStati = Emailstatus.AllList().Where(x => x.Id.In(TagIds)).ToList();
List<Emailgesendetview> emails = Emailgesendetview.AllListByBenutzerIdAndEmailStatus(benutzerId, emailStati, start, anzahl);
if (id == "1,2")
ViewBag.position = 1;
else if (id == "1")
ViewBag.position = 2;
else
ViewBag.position = Int32.Parse(id);
return PartialView("EmailGesendet", emails);
}
}
A click on the middle-right navigation bar triggers the follow code:
<li id="menu2">
#Ajax.RawActionLink(string.Format("<i class='fa fa-circle'></i> Unread"),
"EmailPartial",
"Email",
new { id = "1", module = "1", start = 0, anzahl = 100 },
new AjaxOptions()
{
HttpMethod = "GET",
AllowCache = false,
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "emailBody"
},
new { #class = "class"})
</li>
Everything works fine.
Now i want to add some submenu items to the navbar on the left but i have no idea ( okay i have a bad one... ) how to call the index page before i call the Partialview.
Okay let me explain a litte bit more my problem...
If the user is one the Email page i could easy use the same code but if the user is on a different page (maybe support or something else) and he clicks now on the Outbox link. Now i should call the Index Email page with the outbox partial view.
So i see 2 little problems,
Before i call the Email index page, i must check on which page i am actually because i dont want to reload the complete page if i am at the Email index page with another partial view. At this moment i only want to reload the partial view with a new model. (That step is easy).
My idea to check on which page i am, is to set a "pagestatus" in my viewbag. Is there a better option?
So now if i am on a other page then Email, i cant call the partial view because i have to call the Email Index page before.
My (i think it is a bad idea) is to create different Email index pages (Index1, Index2, Index3). These Pages could have different partial view call like this:
Index1:
<div id="emailBody">
#Html.Action("EmailPartial", new { module = "1", id = "1,2" })
</div>
Index2:
<div id="emailBody">
#Html.Action("EmailPartial", new { module = "2", id = "1" })
</div>
Index3:
<div id="emailBody">
#Html.Action("EmailPartial", new { module = "3", id = "1" })
</div>
So my solution is:
Check on which page i am and if i am on a different Controller, call the Index which i need.
I think that is not a "clear" solution.
Has anyone a better solution? Creating pages for different partialview calls does not sound good...
Thank you
I'm stuck with a very basic detail in a view.
I want to be able to let the user filter the results in the Index view.
To do this I've created a dropdown list, which gets populated thourgh my viewmodel:
#using (Html.BeginForm("Index", "Captains", FormMethod.Get)) {
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty), new { id = "FilterList" })
</div>
</div>
#* ... *#
}
Additionally I have a small jQuery snippet to submit the form on the change event:
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
form.submit();
});
The route I have created for this looks like this:
routes.MapRoute(
name: "IndexFilter",
url: "{controller}/{action}/{Name}",
defaults: new { Name = UrlParameter.Optional}
);
After the submit event I get redirected to the url /Index?Name=ChosenValue
This is filtering totally correct. However I'd like to get rid of the querystring and transform the route to /Index/ChosenValue.
Note: "Name", "ChosenValue" & "SomeProperty" are just dummy replacements for the actual property names.
Instead of submitting the form, you can concatenate /Captains/Index/ with the selected value of the dropdown and redirect to the url using window.location.href as below
$('#FilterList').on('change', function () {
window.location.href = '/Captains/Index/' + $(this).val();
});
I think you're looking for the wrong routing behavior out of a form submit. The type of route resolution that you're hoping to see really only happens on the server side, where the MVC routing knows all about the available route definitions. But the form submission process that happens in the browser only knows about form inputs and their values. It doesn't know that "Name" is a special route parameter... it just tacks on all the form values as querystring parameters.
So if you want to send the browser to /Index/ChosenValue, but you don't want to construct the URL from scratch on the client, you need to construct the URL on the server when the view is rendering. You could take this approach:
<div class="row">
<div class="dropdown">
#Html.DropDownList("Name", new SelectList(Model.SomeProperty),
new {
id = "FilterList",
data_redirect_url = #Url.Action("Index", "Captains", new { Name = "DUMMY_PLACEHOLDER" })
})
</div>
</div>
Above you're setting the URL with a dummy "Name" value that you can replace later, then you'll do the replacement with the selection and redirect in javascript:
$('#FilterList').on('change', function () {
var redirectUrl = $(this).data('redirect-url');
window.location.href = redirectUrl.replace("DUMMY_PLACEHOLDER", $(this).val());
});
If you are wanting to drop the query string off the url because it looks weird, then change your FormMethod.Post.
However, to really answer your question, I've tried the following successfully (Note: this might be considered a hack by some)
In short: update the action url on the form element when the list changes, client side.
$('#FilterList').on('change', function () {
var form = $(this).parents('form');
var originalActionUrl = form.attr("action");
var newActionUrl = originalActionUrl + "/" + $(this).val();
form.attr("action", newActionUrl);
console.log(form.attr("action"));
form.submit();
});
You will need to change your controller's signature to match whatever optional param value you specify in your route config. In your example, "Name".
Note - this is an asp.net MVC 4 application using Razor 2 views...
basically I have a textbox in a view waiting for the user to input data,
this data makes up the values for properties of a model which I want to save to the Db.
The data associated with this textbox has a [required] tab in the Model. I cannot save the model without a value for this textbox as the Model is not valid.
I know I can simply add #Value to the #HtmlTextBoxFor line, put this means that value is displayed to the user.
Is there away to have a default value hidden, so that the user only see's the placeholder text but the "value" will be saved to the Db.
Any ideas...?
textbox..
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "Title"})
controller
if (ModelState.IsValid)
NewsArticle newNews = new NewsArticle();
newNews.Title = newsArticle.Article.Title;
You can add an ID to the textbox as follows:
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "", #id="txtTitle"})
Then call following jquery function on form submit event
$(function(){
$("form").submit(function () {
if($("#txtTitle").val() == ""){
$("#txtTitle").val("Default Value");
}
});
});
I have a simple question (may not be a simple answer!) with the WebGrid in MVC4.
I have a functional Grid like so
<div id="Submitted">
#Html.Grid(
Model.Submitted, displayHeader: false, fieldNamePrefix: "Submitted_", ajaxUpdateContainerId: "Submitted",
columns: new WebGridColumn[]{
new WebGridColumn(){ ColumnName = "Date",Header = "Date",Style = "",CanSort = false,Format = x => x.Date.ToString(Globals.Default.DATEFORMAT) },
new WebGridColumn(){ ColumnName = "ID",Header = "Review",Style = "", CanSort = false, Format = x=>#Html.ActionLink("Review","Review","Company",new{ID = x.ID },new{}) }
})
</div>
When reloading the "Submitted" div with Ajax when the next page button is clicked, it generates the next page fine - but it's going to the original action on the controller, which should be a full page.
How does it filter out everything other than the grid itself? with some clever C# code or jQuery?
EDIT:
To clarify, I'm not asking how to do the paging better, or myself, as far as I'm concerned the default paging with the webgrid is working perfectly as it should - I'm asking how the WebGrid does it's ajax paging when posting back to an action which is returning a FULL page.
It does this using jquery load() and functionality that allows it to select just the relevant incoming nodes. This is taken from http://msdn.microsoft.com/en-us/magazine/hh288075.aspx
To allow the script to be applied just to a WebGrid, it uses jQuery selectors to identify elements with the ajaxGrid class set. The script establishes click handlers for the sorting and paging links (identified via the table header or footer inside the grid container) using the jQuery live method (api.jquery.com/live). This sets up the event handler for existing and future elements that match the selector, which is handy given the script will be replacing the content.
You should put your grid in a partialview and update it by Ajax. In controller you should find the request's type. If it is a ajax request(by Request.IsAjaxRequest() ) you must return the partialview, otherwise you must return the original view.
If you are using ajax.beginform you must do something like this:
#using (Ajax.BeginForm("Index", new AjaxOptions { OnFailure = "searchFailed", HttpMethod = "POST", UpdateTargetId = "Submitted" }))
{
...
}
<div id="Submitted">
#Html.Partial("_partialviewname", Model)
</div>
rn
and in controller:
public ActionResult Index(int? page)
{
...
if (Request.IsAjaxRequest())
{
return PartialView("_partialviewname", db.model)
}
return View(db.model)
}
I have such an action method:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Search(String filter, String value, Int32? page) {
var set = new List<Employee>();
switch(filter) {
case "by-name": {
set = this.repository.Get(
e => (e.LastName + " " + e.FirstName + " " + e.MiddleName) == value
).ToList();
break;
}
case "by-empn": {
set = this.repository.Get(
e => e.EmployeeNumber == value
).ToList();
break;
}
default: return RedirectToAction("Search", "Employee");
}
ViewBag.SearchedEmployees = set.Count();
return View(set.ToPagedList(page ?? 1, PageSize));
}
Search view is like this:
#if(Model.Count > 0) {
foreach(var item in Model) {
Html.RenderPartial("Employee.Card", item);
}
#Html.PagedListPager(
Model,
page => Url.Action("Search", new { page = page }),
new PagedListRenderOptions {
LinkToFirstPageFormat = "<< Beginning",
LinkToPreviousPageFormat = "< Back",
LinkToNextPageFormat = "Forth >",
LinkToLastPageFormat = "End >>"
}
)
}
Search form is presented as a partial view:
#using(Html.BeginForm("Search", "Employee", FormMethod.Get, new { #class = "search-form" }))
{
<p>
#Html.TextBox("value")
</p>
<p>
#Html.RadioButton("filter", "by-name", true) By name <br/>
#Html.RadioButton("filter", "by-empn") By empn <br/>
</p>
<p>
<input type="image" src="#Url.Content("~/Content/Images/Search.png")" />
</p>
}
Problem: I have N page links. When I try to go to the second page I face an infinite loop of redirects. That's the way I implemented my action - default case is fired. So filter/value values are null on the second action call? Why?
How do I refactor my search action?
Also how should I configure route for such an action?
Thanks!
EDIT
So should route for the search action look like:
routes.MapRoute(
null,
"{controller}/{action}/Page{page}/filter{filter}/val{value}",
new { controller = "Employee", action = "Search" }
);
?
EDIT 2
So it is possible to write next:
page => Url.Action("Search", new { filter = ViewBag.SearchFilter, value = ViewBag.SearchValue, page = page }),
And inside a controller:
public ActionResult Search(String filter, String value, Int32? page) {
ViewBag.SearchFilter = filter;
ViewBag.SearchValue = value;
// ...
}
Is this right?
So filter/value values are null on the second action call? Why?
Because their corresponding input fields are inside a separate form and are never sent to the server.
You seem to be using some custom Html.PagedListPager helper (the code for which you haven't shown) but I guess that this helper generates the page links as anchors and it simply doesn't take into account any current query string or POSTed values when generating those links. So the href of your pagination link looks like this /SomeController/Search?page=5 instead of the correct one which would take into account those parameters which is /SomeController/Search?page=5&filter=somefilter&value=somevalue.
You can now easily understand why the filter and value parameters in your controller action are always null. It's because you never send them to the server when clicking on the pagination links.
So in order to resolve this issue you could modify this custom HTML helper that you are using to generate the pagination links to include those additional parameters. Or maybe the helper allows you to pass additional parameters? Check the documentation if this is some third party plugin that you are using.