I am trying to add error on my own using ModelState.AddModelError, and when I try to display it on view, validation span is in html, but there is no message.
Controller
if (!paymentTypeId.HasValue || !shipmentTypeId.HasValue)
{
var model = new CheckoutViewModel()
{
ShipmentTypes = m_ShipmentTypeService.GetAllShipmentTypes(true),
PaymentTypes = m_PaymentTypeService.GetAllPaymentTypes(true),
};
SetBaseProperties(model, null);
ModelState.AddModelError("ErrorCheckout", "L_CHOOSE_TYPE_ERROR");
return View(model);
}
View
#Html.ValidationMessage("ErrorCheckout", new { #class = "text-danger" })
On other pages I did same and it worket, I don't know what is problem here
Problem was in sending request to Action via ajax. When I changed to Html.Form and placed submit, it started working, strange behavior, but here you go.
Related
When i use Html.ActionLink without parameter values the destination view's bootstrap loads normally but when I try to pass pa parameter the destination view's bootstrap does not load it only displays simple html without bootstrap. I'm using sb-admin-2 btw.
I have already tried all the method overloading of #Html.ActionLink but nothing works.
When you click this link the page load and data are passed but the bootstrap fails to load.
#Html.Actionlink with parameter code:
#Html.ActionLink("Update", "AddOrEdit", "Receiving", new { #id = item.ReceivingDocumentNo }, new { #class = "btn btn-xs btn-info" })
#Html.ActionLink without parameter code:
#Html.ActionLink("Create New", "AddOrEdit", "Receiving", new { #class = "btn btn-success" })
Please refer to this link to the image results of the views.
https://imgur.com/a/6Jg09tV
Controller Code:
[HttpGet]
public ActionResult AddOrEdit(string id = "")
{
List<DTS.Models.DocumentType> documentTypeList = new List<DocumentType>();
List<Section> sectionList = new List<Section>();
documentTypeList = DapperORM.ReturnList<DocumentType>("ViewAllDocumentTypesReceiving").ToList<DocumentType>();
sectionList = DapperORM.ReturnList<Section>("ViewAllSections").ToList<Section>();
ViewData["DocumentTypeList"] = documentTypeList;
ViewData["SectionList"] = sectionList;
Receiving res = new Receiving();
if (id == "")
{
res.ReceivingDocumentNo = DapperORM.ReturnList<string>("GenerateReceivingTrackingNo", null).FirstOrDefault<string>();
res.ReceivingSections = sectionList;
}
else
{
DynamicParameters param = new DynamicParameters();
param.Add("#ReceivingDocumentNo", id);
res = DapperORM.ReturnList<Receiving>("GetReceivingDetailsForUpdateByReceivingDocumentNo", param).FirstOrDefault<Receiving>();
res.ReceivingSections = DapperORM.ReturnList<Section>("GetReceivingListForUpdateByDocumentNo", param).ToList<Section>();
}
return View(res);
}
The result should be the same with the bootstrap layout rendering normally.
Are your _Layout.cshtml being applied at all? I do believe the problem is not in the submitted code but rather in the view code, and that the information provided is not enough to get a specific answer. -regards.
what i'm trying to achieve:
1. fill up form
2. save into database
3. redirect user to another view that displays some details (referenceID)
so here's what i have
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ClearanceViewModel myViewModel, TClearance clearance, TRefsNum referenceNo)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
string refNo = DateTime.Now.Year + finalString;
items.RefNum = refNo;
db.TClearances.Add(items);
db.SaveChanges();
return RedirectToAction(items.RefNum, "displayRef");
}
code above does save to database whatever user has input then redirect to view "displayRef" and items.refNum is the value that i'm trying to pass to view
view:
#model RDMSPNPOnlineClearance.Models.TClearance
#{
var getRef = Model.RefNum;
}
this is your ref number: #Html.LabelFor(model => model.RefNum, htmlAttributes: new { #class = "control-label" })
code above, is trying to get the expected value "items.refNum" and use the value to display it to the user.
so what actually happening is, user fill ups, saves to db, then redirected to "displayRef" view. no problem in saving part. the problem is im not getting the refNum in the displayRef view. the url changes to something like:
Localhost:55433/items.refNum/view
so, how do i pass that value to be displayed to the user?
Do you need RedirectToAction? Can you not just return the view...
return View("displayRef", items.RefNum);
If you have to use RedirectToAction, this means you're redirecting to a controller action and you must specify it like so...
return RedirectToAction("Action","controller", new {#id=id});
Also your model in the view is incorrect, you're binding a string refNo, but at the top of your view stating that you want to bind a class RDMSPNPOnlineClearance.Models.TClearance
I have an application where I need to input data and on submit the data gets saved in database. When I checked in database the input is getting saved successfully but I am getting an exception when the page reloads after httppost.
I am getting exception at :
#Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, #class = "form-control" })
controller code to get the dropdownlist values, binding with Db:
[ActionName("DetailsForm")]
[HttpGet]
public ActionResult DetailsForm()
{
try
{
var model = new DetailsViewModel() { dropConfig = floorService.DropDownList().ToList() };
return View("DetailsForm", model);
}
catch (Exception ex)
{
return View("_error");
}
}
controller code to http post:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.LineID = Convert.ToString(form["LineID"]);
//Similary for other fields
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm",model);
}
Snapshot of exception:
Because your view code is using Model.dropConfig to build the SelectList for your dropdown, and you are not setting the dropConfig property value before returning to the view.
Remember, Http is stateless. So even though you set the dropConfig property value in the GET action, It won't be available inside your HttpPost action. When you submit your form, it is a totally new request to the server.
You can fix it by loading dropConfig property again.
model.dropConfig = floorService.DropDownList().ToList();
return View(model);
But ideally you should be following the P-R-G pattern.
P-R-G stands for Post-Redirect-Get. So when you submit your form to an http post action method, you should return a redirect response and the browser will make a new GET call to that action method.
You can use the RedirectToAction method to return a redirect response.
floorService.SaveDetails(detailsConfig);
return RedirectToAction("DetailsForm");
This will send a 302 response back to the browser with the location header set to the url to the DetailsForm action method and the browser will make a new GET request to that.
ViewBag won't work when with redirect response. So you might consider using TempData. TempData can be used to transfer between two requests.
TempData["message"] = "Success";
return RedirectToAction("DetailsForm");
Now you can read TempData["message"] in the DetailsForm action method or the view rendered by that.
For example, you can read it in the view (rendered by DetailsForm GET action method) like this
#if (TempData["message"]!=null)
{
<div class="alert alert-success" id="alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong>#TempData["message"]
</div>
}
I have dynamically created radio buttons in my view and i am trying to pass the checked value to my controller. When my controller is hit the Agentcode string is Empty and i cant figure out how to grab the value so i can send it to my controller.
EDIT my radio buttons are generated in a foreach which i think may be causing the difficulty in reaching the value.
This is what the html rendered by the MVC control looks like
<div>
<input name="XXXXX" type="radio" value="{ data_bind = checkedValue: $data,checked: $root.AgentCode }">
</div>
foreach (var code in Model.ActiveAgentCodes)
{
<div>
#Html.RadioButton(code.AgentCode, new { data_bind="checkedValue: $data,checked: $root.AgentCode"})
#Html.RadioButton(code.AgentCode, new {data_bind="checkedValue: $data,checked: $root.AgentCode"}) }
my knockout ViewModel looks like this.
function ViewModel(){
var self = this;
self.AgentCode = ko.observable();
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
and the post method in my controller looks like this
[HttpPost]
public ActionResult GetAgentCodeForHomeController(string AgentCode)
{
return RedirectToAction("Home", "Home");
}
In my view i am posting using like so
#using (Html.BeginForm("GetAgentCodeForHomeController", "ChangeAccount"))
{
#Html.RadioButton(code.AgentCode, new {data_bind="checkedValue: $data,checked: $root.AgentCode"})
#Html.HiddenFor(model => model.AgentCode, new { data_bind = "text:AgentCode" })
}
<button type="submit">OK</button>
I needed to send data back to my controller and the best way that i found was to add properties to my viewmodel.
public string AgentCode {get; set;}
Then give the radio buttons an Id so that when the controller is hit MVC maps the properties correctly. I decided to not go with knockout and instead post the form back to the controller. It ended up looking like this on my buttons.
#Html.RadioButton("AgentCode", code.AgentCode, new {id = code.AgentCode})
I have multiple index views with a different grid in each of these views, but all of them uses the same popup control. I dont want to make a partial view foreach index view that i have. So i put the popup partial view in the Shared folder.
But i have a Html.BeginForm('Action','Controller') in the popup partialview, and these values are different in each grid. How can i pass these from the view of the grid to the partial view of the popup?
The Grid View:
//Code Resumed
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "TestMasterGrid";
settings.Column.Add("Id");
settings.Column.Add("Name");
settings.Column.Add("Email");
//Command Column Wich calls the popup control
}
The PopUp PartialView:
//Code resumed
using (Html.BeginForm("ActionINeedToGetFromTheGridView", "ControllerINeedToGetFromTheGridView", FormMethod.Post))
{
Html.DevExpress().TextBox(
textBoxSettings =>
{
textBoxSettings.Name = "reason";
textBoxSettings.ControlStyle.CssClass = "editor";
})
.Render();
Html.DevExpress().Label(
labelSettings =>
{
labelSettings.Name = "sh";
labelSettings.ControlStyle.CssClass = "label";
}).Render();
Html.DevExpress().Button(
buttonSettings =>
{
buttonSettings.Name = "btnUpdate";
buttonSettings.ControlStyle.CssClass = "button";
buttonSettings.Width = 80;
buttonSettings.Text = "OK";
buttonSettings.UseSubmitBehavior = true;
}
)
.Render();
Thanks!
Pass the action and controller names to the action that returns the PartialViewResult. Then, pass the names to the partial's model and use them in the BeginForm statement:
Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post)
Edit:
I'm not very familiar with DevExpress, but I found the CallbackRouteValues member in settings. I'll use that for my example:
settings.CallbackRouteValues = new { Controller = "ControllerName", Action = "GetPartialView", desiredAction = "DesiredAction", desiredController = "DesiredController" }
In your controller, you'd have the action and controller parameters:
public PartialViewResult GetParialView(string desiredAction, string desiredController) {
var viewModel = new PartialViewModel { Action = desiredAction, Controller = desiredController);
Return PartialView("Name", viewModel);
}
I typed out this code by hand, so it's probably full of errors. Hopefully it gets the idea across, though.
Quick edit: changed some parameter names to make it a little clearer.