How can I pass NextPrevious value to controller?
Now NextPrevious is getting always null
[HttpPost]
public ActionResult PremiumUserRegistration(PartnersVM partnersVM, string NextPrevious)
{
if (NextPrevious != null)
{
}
}
View And .js file,
$('.btnActionNext').click(function () {
$(this).closest('form')[0].submit();
});
#Html.ActionLink("Next >>", "PremiumUserRegistration", new { controller = "UserRegister" }, new { NextPrevious = "value", #class = "btnActionNext" , onclick = "return false;" })
Please help me...
Add a hidden:
<input type="hidden" name="Action" />
Make sure it's on your form. Next, on your click handler, do:
$('.btnActionNext').click(function () {
$("#Action").val("NEXT");
$(this).closest('form')[0].submit();
});
In your post action, add string Action:
[HttpPost]
public ActionResult PremiumUserRegistration(string Action, PartnersVM partnersVM)
{
if (Action == "NEXT")
{
}
}
If you are submitting a form, then add it as a hidden field
#Html.Hidden("NextPrevious", value)
Otherwise, you entered the "NextPrevious" value in the wrong spot in the ActionLink method. It should be within routeValues, not htmlAttributes.
The correct way would be:
#Html.ActionLink("Next >>", "PremiumUserRegistration", new { controller = "UserRegister", NextPrevious = "value" }, new { #class = "btnActionNext", onclick = "return false;" })
Related
I'm making a post request from on view so that I don't see the parameters on the URL and I can tell it is passing the appropriate parameters to controller for the request but it does not display the appropriate view from that controller.
Calling view
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST"
})
WorkItems Controller method
[HttpPost]
public ActionResult NewIndex(NewWorkItemViewModel vm)
{
vm.IsValid = ModelState.IsValid;
vm.HandleRequest();
if (vm.IsValid)
{
// NOTE: Must clear the model state in order to bind
// the #Html helpers to the new model values
ModelState.Clear();
}
else
{
foreach (KeyValuePair<string, string> item in vm.ValidationErrors)
{
ModelState.AddModelError(item.Key, item.Value);
}
}
return View(vm);
}
Putting a breakpoint on the last Return View(vm) confirms it is being called but the browsers does not update to display the workItems view.
Suggestions on why the browser is not being updated to display the appropriate view.
You're making an ajax post, the newly rendered view is being returned by the server if you were to look in the network console in your browser. Add a success callback. Either assign a callback to handle the response or use the
UpdateTargetId property in your AjaxOptions
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "AjaxSuccess", //handle with callback
UpdateTargetId = "MyElementID" //update html element
})
if you choose to use OnSuccess then in javascript
function AjaxSuccess(data){
//handle response
}
AjaxOptions properties and usage can be found here
EDIT
You could use javascript to submit a form when a link is clicked, put a form somewhere in your code and hide it.
#using (Html.BeginForm("NewIndex", "WorkItems", FormMethod.Post,
new { class = "hidden", id = "postForm" } ))
{
<input type="hidden" name="eventCommand" value="createforrig" />
<input type="hidden" name="eventArgument2" value="#item.Id" />
<input type="submit" value="link text" id="submitForm"/>
}
then change your #Ajax.ActionLink... to
#Html.ActionLink("Work1", "NewIndex", "WorkItems", new { id = "postLink"})
and if you're using jQuery
<script>
$(function(){
$('#postLink').click(function(e)
{
e.preventDefault();
$('#postForm').submit();
});
});
</script>
and don't forget to hide the form in css
.hidden { display:none;}
I have a dropdown control have two type of values 'Contractor' and 'Full time', based on the dropdown selection relevant controls will be displayed.
Now when i click on the submit button i have to redirect to different action method (i.e) when 'Contractor' is selected it should redirect to AddContractor() else it should redirect to Full time along with the filled information.
How to implement it using single Html.Beginform()
Ok you can do:
On View:
#{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Contractor", Value = "0" });
items.Add(new SelectListItem { Text = "Full time", Value = "1" });
}
#using (Html.BeginForm("Go", "Home", FormMethod.Post))
{
#Html.DropDownList("Example", items)
<input type="submit" value="Submit" />
}
<p>Value selected: #ViewBag.Info</p>
On Controller:
[HttpPost]
[AllowAnonymous]
public ActionResult Go(int example)
{
if (example != null)
{
if (example == 0)
{
return RedirectToAction("AddContractor", new { info = example});
}
else
{
return RedirectToAction("Other", new {info = example});
}
}
return View("Index");
}
public ActionResult AddContractor(int info)
{
ViewBag.Info = info;
return View("Index");
}
public ActionResult Other(int info)
{
ViewBag.Info = info;
return View("Index");
}
You can use another view and other info for your project. I just code example to redirect action and model info.
Hope can help you :)
I have an MVC view, which is launched by a function in the controller. That view has a button that I want to use to submit data to a different function in that same controller, but it always go back to the function that launched it instead.
The controller is called, the ViewForPrepare view is launched from PrepareList, I hit the button on ViewForPrepare, and it submits to PrepareList again instead of RunList.
In the controller I have:
public ActionResult PrepareList(int Key)
{
return "ViewForPrepare";
}
public ActionResult RunList(int Key)
{
return "OtherView";
}
Then in the View:
<input type="button" value="Submit Report" id="submit">
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () { window.location ='#Url.RouteUrl("RunList", new { Key = #Model.caseNumber })' });
});
</script>
So I press the button to go to RunList, but it keeps going to PrepareList. I've checked the routing and it looks OK. What do I need to do to get the button to submit to RunList?
You're code right now basically says "When I click the submit button. Change the window's location to something else." If that is what you want, try using
#Url.Action("RunList", new { Key = Model.caseNumber })
instead of
#Url.RouteUrl("RunList", new { Key = #Model.caseNumber })
and try using a <button> element instead of an <input> element.
If what you want is to post the data from the form, you should wrap your button in a form tag (make sure to replace "ControllerName" below with your actual controller.)
#Html.BeginForm("RunList","ControllerName", new { Key = Model.caseNumber })
{
<input type="submit" value="Submit Report" id="submit">
}
and get rid of the javascript altogether as it isn't necessary in this case. Also you will have to mark your RunList action as HttpPost for this to work.
[HttpPost]
public ActionResult RunList(int Key)
{
return "OtherView";
}
Why dont you just use a RouteLink instead of the Input?
#Html.RouteLink("Submit Report", "RunList", new { Key = Model.caseNumber }, new {#class="btn" })
not sure if you're using bootstrap or jquery ui but there are css classes to make links look like buttons.
ActionLink works the same way.
#Html.ActionLink("Submit Report", "RunList", "ViewForPrepare ", new { Key = Model.caseNumber }, new { #class = "btn" })
Using VS2015 Pro I created a project using the MVC template.
HomeController.cs added:
public ActionResult PrepareList(int Key)
{
return View();
}
public ActionResult RunList(int Key)
{
return View(); ;
}
Index.cshtml added:
#Html.ActionLink("Submit Report", "RunList", new { Key = 4 }, new { #class = "btn" })
Put a break point in "RunList" and it worked!
Using
<input type="button" value="Submit Report" id="submit">
#section script{
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () { window.location ='#Url.RouteUrl("RunList", new { Key = 4 })' });
});
</script>
}
I got the meessage
A route named 'RunList' could not be found in the route collection.
when you need to send data, you must add the attribute HttpPost to this action:
[HttpPost]
public ActionResult RunList(int Key)
{
return "OtherView";
}
I am trying to add a remove/delete a dynamically created partial view.
This is my ADD script.
$("#btnAdd").on('click', function () {
$.ajax({
async: false,
url: '/Employees/Add'
}).success(function (partialView) {
$('#AddSchedule').append("<tbody>" + partialView + "</tbody>");
});
});
this is the add controller
public ActionResult Add()
{
var schedViewModel = new FacultySchedViewModel();
return PartialView("~/Views/Employees/_DynamicView.cshtml", schedViewModel);
}
this is the partial view _DynamicView.cshtml
#using(Html.BeginCollectionItem("New")){
<td>
#Html.ActionLink("Delete", "DeleteThis", "MyController", null)
</td>
<td>
#Html.EditorFor(model => #Model.Schedule, new { htmlAttributes = new { #class = "form-control" } })
</td> }
what i can't figure out are
how to get the ID generated by BeginItemCollection
use the ID in a remove script
action on the controller
EDIT
1. How to connect it to a button or a link for removing the row
Added the view on the the Main of the partial view
#for (int i = 0; i < #Model.New.Count(); i++)
{
#Html.EditorFor(model => #Model.New[i])
}
The BeginItemCollection add a Guid as an indexer to the controls name and id attributes. It has no relevance at all to identifying an item to delete. You need add include the value of the property that identifies the FacultySchedViewModel object. Assuming its int ID, then change the partial to include a button and add the ID as a data- attribute
#using(Html.BeginCollectionItem("New"))
{
<tr>
<td><button type="button" class="delete" data-id="#Model.ID">Delete</button></td>
<td>#Html.EditorFor(model => #Model.Schedule, new { htmlAttributes = new { #class = "form-control" } })</td>
</tr>
}
Then your script would be
var url = '#Url.Action("Delete")'; // assumes its in the same controller
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr');
if (id) { // or if(id == 0) depending if your property is nullable
row.remove(); // the item never existed so no need to call the server
return;
}
$.post(url, { ID: id }, function(response) {
if(response) {
row.remove(); // OK, so remove the row
} else {
// Oops - display and error message?
}
});
});
and the controller
[HttpPost]
public JsonResult Delete(int ID)
{
// Delete the item in the database
return Json(true); // or if there is an error, return Json(null); to indicate failure
}
Side note:
$('#AddSchedule').append("<tbody>" + partialView + "</tbody>"); is
adding a new tbody element for each item. Instead the main view
should include the tbody element and give it the id so its
$('#AddSchedule').append(partialView); or use $('#AddSchedule
tbody')append(partialView);
Does the model your posting back really have a property named New
(as you indicate in the BeginItemCollection method)?
As per your html render, what I suggest to modify your partial view as
From
#Html.ActionLink("Delete", "DeleteThis", "MyController", null)
To
#Html.ActionLink("Delete", "DeleteThis", "MyController", new { hidefocus = "hidefocus" } ) //add custom properties for here, which you can grab at client side or give css here.
Now search the anchor link via jQuery: Find the element with a particular custom attribute
When you get id, you can go parent like $('#id').parent().parent().hide() or empty()
or
As second option, is on click of Delete button call the same controller , but with a parameter to identify delete, so while returning give the null will bind in ajax again with empty string.
Why does Html.ActionLink render "?Length=4"
http://forums.asp.net/t/1787278.aspx?Add+and+remove+partial+views
I have a jquery function to check valid data on UsernameTextbox in my View. I want to prevent User click on the Register button until this field valid.
Disable button is it the best method? I just want when the value is not valid, user click on button just focus to the UsernameTextbox filed?
Update Code:
Here is my Model :
[Required]
[Remote("CheckUsername", "Account", ErrorMessage = "Username already exits.")]
public string Username { get; set; }
and Controller with GET method:
[HttpGet]
public JsonResult CheckUsername(string userName)
{
var user = IUserRepo.GetUserByUrName(userName);
bool isValid = true;
if (user!=null)
{
isValid = false;
}
return Json(isValid, JsonRequestBehavior.AllowGet);
}
and in my View :
#using (Ajax.BeginForm("Register","Account",new {area = "Area"},null))
{
#Html.ValidationSummary(true)
<table>
<tbody>
<tr>
<td class="info_label">Tên đăng nhập</td>
<td>#Html.EditorFor(m => m.User.Username)
</td>
<td class="check_user">#Html.ValidationMessageFor(m => m.User.Username)</td>
</tr>
<tr> ........
Why no error message appear? And i want to valid intermediately when user fill data or leave textbox like this site http://yame.vn/TaiKhoan/DangKy.
Note : The below mentioned suggestion is only for MVC3 and above
Luffy, you can remove the Ajax Call to check UserName existence
How can we do that ?
Model
public class UserModel
{
// Remote validation is new in MVC3. Although this will also generate AJAX
// call but, you don't need to explicitly type the code for Ajax call to
// check the User Existence. Remote Validation will take care of it.
[Required]
[Remote("CheckUsername", "Account", ErrorMessage = "User Already Exist")]
public string UserName { get; set; }
}
Controller
[HttpGet]
public JsonResult CheckUsername(string MyProp)
{
// Your Validation to check user goes here
bool isValid = true;
return Json(isValid, JsonRequestBehavior.AllowGet);
//Note - This will be called whenever you post the form.
//This function will execute on priority, after then the Index
//Post Action Method.
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(UserModel model)
{
// This action method will execute if the UserName does not exists
// in the DataBase
return View(model);
}
View
#using (Ajax.BeginForm("Action", "Controller", new { area = "Area" }, null))
{
#Html.TextBoxFor(i => i.UserName);
<input type="submit" name="Submit" value="Submit" />
// Whenever you submit the form, the control will go directly to
// CheckUsername function. In case the UserName doesn't exists only
// then the Post action method will be executed.
}
Scripts
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
Try this
function CheckUserNameExits() {
$("#User_Username").on("blur", function () {
$("#User_Username").addClass("thinking");
var username = $("#User_Username").val();
if (username == "") {
$(".check_user").html("Ba?n chua nhâ?p tên dang nhâ?p.");
$("#User_Username").removeClass("thinking");
$("#User_Username").removeClass("approved");
$("#User_Username").addClass("denied");
$("#User_Username").focus();
$("#User_Username").select();
return false;
}
$.ajax({
url: "/Account/CheckUsername",
data: { userName: username },
dataType: "json",
type: "POST",
error: function () {
return false;
},
success: function (data) {
if (data) {
$("#User_Username").removeClass("thinking");
$("#User_Username").removeClass("denied");
$("#User_Username").addClass("approved");
$(".check_user").html("");
//$("#createuser").prop("disabled", false);
return true;
}
else {
$("#User_Username").removeClass("thinking");
$("#User_Username").removeClass("approved");
$("#User_Username").addClass("denied");
$(".check_user").html("Tên dang nhâ?p da~ duo?c du`ng, vui lo`ng cho?n tên kha´c.");
$("#User_Username").focus();
$("#User_Username").select();
//$("#createuser").prop("disabled", true);
return false;
}
}
});
});
}
function CheckValidate()
{
if (!CheckUserNameExits()){
return false;
}
return true;
}
<input id="createuser" type="submit" value="Ðang ky´ ta`i khoa?n" onclick="return CheckValidate();" />
May be it would be better to use jQuert enable/disable button method.
Fistly button is disable:
$(document).ready(function(){
$( ".register" ).button("disabled");
});
Than, if your function return true, enable button
function CheckUserNameExits() {
//*If your function is success
$( ".register" ).button( "enable" );
})