I have a view that design view like :
Here i impose some entry validation when click save button I want to display me error message in my expecting display region. How can it possible?
My Controller Action is :
[HttpPost]
public ActionResult Save(COA_ChartsOfAccount oCOA_ChartsOfAccount)
{
try
{
if (this.ValidateInput(oCOA_ChartsOfAccount))
{
COA_ChartsOfAccount oParent = new COA_ChartsOfAccount();
oParent = oParent.Get(oCOA_ChartsOfAccount.ParentHeadID);
if (oCOA_ChartsOfAccount.IsChild)
{
oCOA_ChartsOfAccount.ParentHeadID = oParent.AccountHeadID;
}
else
{
oCOA_ChartsOfAccount.ParentHeadID = oParent.ParentHeadID;
}
oCOA_ChartsOfAccount = oCOA_ChartsOfAccount.Save();
return RedirectToAction("RefreshList");
}
return View(oCOA_ChartsOfAccount);
}
catch (Exception ex)
{
return View(oCOA_ChartsOfAccount);
}
}
Note : I want to make common partial view for error message display. (Like exception error message, validation message, all kind of user notification message)
With your current set up
To display an error message
In your controller:
catch (Exception ex)
{
TempData["message"] = "Custom Error Messge";
return View(oCOA_ChartsOfAccount);
}
In your view:
<div style="color: red;font-weight:900;">#TempData["message"]</div>
Related
the custom error message doesn't displaying the error,it only shows blank page instead error message
here is my controller :
public function daftar(){
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('nama','Nama','required');
$this->form_validation->set_rules('pass','Password','required');
$this->form_validation->set_rules('passconf','PasswordConf','required|matches[pass]');
if($this->form_validation->run()==FALSE){
$this->form_validation->set_message('passconf','the password doesnt match');
}
else{
redirect('lowongan/daftar_employer');
}
}
}
You need to escape the apostrophe in the word "doesn't".
$this->form_validation->set_message('passconf','the password doesn\'t match');
write a custom callback function to set your own error message
callback_custom_error
$this->form_validation->set_rules('passconf','PasswordConf','required|matches[pass]|callback_custom_error');
public function custom_error($str)
{
if($this->form_validation->run()==FALSE)
{
$this->form_validation->set_message('passconf','your custom message');
return FALSE;
}
else
{
return TRUE;
}
}
I have a simple form with a textbox (and a model editor I want to render in specific cases)
#using (Html.BeginForm("Import", "Flow"))
{
#Html.TextBoxFor(model => model.IsConfirmed)
#if (Model.IsConfirmed)
{
#Html.EditorFor(m => m.Preview)
}
}
The model used in this view is the following
public class ImportViewModel
{
public Boolean IsConfirmed { get; set; }
public PreviewViewModel Preview { get; set; }
public ImportViewModel()
{
this.IsConfirmed = false;
}
}
The form posts on the following controller
public class FlowController
{
[HttpPost]
public ActionResult Import(ImportViewModel model)
{
try
{
if (ModelState.IsValid)
{
if (model.IsConfirmed)
{
// do something else
}
else
{
model.Preview = Preview(model.strCA, model.SelectedAccount);
model.IsConfirmed = true;
return View(model);
}
}
}
catch (Exception ex)
{
throw new Exception("arf", ex);
}
return RedirectToAction("Index", "Home");
}
}
On first load, the textbox contains "false"
When posted, the property IsConfirmed of the model is set to "true" and this model is passed to the same view.
I expect the textbox to be "true" but it is still "false"... moreover the Preview property is correctly rendered, so it means Model.IsConfirmed is indeed true...
Am I missing something ?
Thanks
Make sure you remove the value from the ModelState if you intend to modify it:
ModelState.Remove("IsConfirmed");
model.IsConfirmed = true;
The reason you need to do that is because, by design, all Html helpers (such as TextBoxFor) will first look for a value in the ModelState when binding and only not found they will use the value on your model. And since there's a value with the same name in the ModelState (coming from the POST request), that's what's being used.
I have been using Telerik controls, I was using server binding, but I have to use Ajax binding, that is not working properly, I am getting Error "Error! The requested URL did not return JSON asp.net mvc"
Following is the Code in My Controller
[GridAction]
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
Contact model = _cService.getContact(id, applicationID);
GetContactType();
if (model != null)
return View(model);
else
return View();
}
//
// POST: /Contact/Edit/5
[GridAction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Contact model)
{
try
{
_cService.SaveContact(model, applicationID);
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}
and following Code in my view
#(Html.Telerik().Grid(Model)
.Name("Contact")
// .ToolBar(commands => commands.Insert())
.DataKeys(keys => keys.Add(c => c.Id))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Update("Edit", "Contact", new { mode = GridEditMode.InForm, type = GridButtonType.Text })
.Delete("Delete", "Contact", new { mode = GridEditMode.InLine, type = GridButtonType.Text });
})
What I can do this Error, this error arise using Alert box, I have tried Modifying telerik.grid.min.js I have removed the line that shows an alert box,then it does not shows me error but also does not work.
Can somebody please give me Some suggestions.
Thank You
This is not a prompt response but as I'm addressing this issue now I can answer it. This is likely caused by the fact that your session has timed out, resulting in IIS to redirect to your login page. As it's the login page which is being returned, not the expected JSON, you get this message. You can trap for this error as follows:
var checkForSessionTimeout = function (e) {
logOnResponse = e.XMLHttpRequest.responseText.match(/.*<title.*>(Log On)<\/title>.*/);
if (logOnResponse.length > 0 || e.XMLHttpRequest.status === 401) {
alert("Your session has expired. You will be redirected to log on.");
location.href = logOnUrl;
}
}
Of course, you'll have to define logOnUrl to point to your page.
A follow on question, should you have found the answer on your own, any idea how to prevent the actual error alert since we're providing our own?
I'm again struggling at validating inputs.
Let's say I edit a customer and the field "name" is required via
[Required(ErrorMessage = Constants.ErrorMsgNameMissing)]
public string NAME { get; set; }
inside the model.
The edit method does
[HttpPost]
edit(ViewModel vm)
{
// some code here
try
{
UpdateModel(vm);
// some code there
}
catch (Exception e)
{
return View(vm);
}
}
While doing UpdateModel(vm), an exception is thrown if the name is empty. Then my view shows the Html.ValidationSummary(). So far, so good.
Now, if I create a customer via
[HttpPost]
create(ViewModel vm)
{
if (ModelState.IsValid) { ... }
}
I don't have the method UpdateModel() since there's nothing to update. And ModelState.IsValid seems to return true every time. Even if the ViewModel is null. So I run into trouble then.
How do I validate this? And what do I return in case of errors?
Update: I think it was too late yesterday. In fact, it DOES work. But I was hoping for an exception and forgot the else { ... }...
Try this:
[HttpPost, ValidateInput(true)]
create(ViewModel vm)
{
if (ModelState.IsValid) { ... }
}
How can I pass the exception thorwn by the action in MVCContrib.FluentController CheckValidCall(action)?
[ExportModelStateToTempData]
public ActionResult Index(int itemId, int page)
{
return CheckValidCall(() => MyService.GetResults(itemId, page))
.Valid(x => View(x))
.Invalid(() => RedirectToAction(RestfulAction.Index));
}
When GetResults() throws exception I want to display it in the view. I've tired ModelState
<%if (ViewData.ModelState.ContainsKey("_FORM")) {%>
<div class="notificationError">
<%= ViewData.ModelState["_FORM"].Errors.FirstOrDefault().ErrorMessage %>
</div>
<%}%>
but the ModelState is valid and contains no errors. Is there any way to access the exception message without wrapping service method in try-catch block? If it helps here is my unit test to check ModelState which fails as TestController.ModelState.IsValid is true:
[Fact]
public void ServiceExceptionIsConvertedToModelStateErrorInFluentController()
{
// Set up
MockService.Setup(x => x.GetResults(It.IsAny<int>(), It.IsAny<int>()))
.Throws(new InvalidOperationException("Mocked Service Exception"));
// Excercise
Assert.Throws<InvalidOperationException>(() => TestController.GetResults(1, 1));
// Verify
Assert.False(TestController.ModelState.IsValid);
Assert.True(TestController.ModelState["_FORM"].Errors.Count > 0);
}
I've manage to pass exception into ModelState by overriding MvcContrib.FluentController.AbsteactFluentController.ExecuteCheckValidCall(Func action):
protected override object ExecuteCheckValidCall(Func<object> action)
{
try
{
return base.ExecuteCheckValidCall(action);
}
catch (Exception exception)
{
ModelState.AddModelError("_Exception", exception);
return null;
}
}
Which is called by CheckValidCall. However the method is described as "public for testing purposes only and shouldn't be used" the alternative way of doing it is to override MvcContrib.FluentController.AbstractFluentController.CheckValidCall().