c# - Custom model error text in MVC 4 -


background: extremely new mvc, c#, , .net in general. working mvc4 internet application template in visual studio 2012.

i want display model binding errors using bootstrap's alert classes rather unordered list produced html.validationsummary(). hacked mess came with:

stringwriter writer = new stringwriter();  foreach (modelstate state in viewdata.modelstate.values) {     foreach (var error in state.errors) {         writer.write(error.errormessage);         break;         // in case error messages same,         // break out when first one.     } } if (writer.tostring() != "") {     <div class="alert">@writer.tostring()</div> } 

it in login.cshtml view , pops alert style box on failed login.

does have better suggestions on how display model binding errors using custom html/css? threw based on googling , guesswork mostly, advice appreciated.

found similar question: change default validationsummary template in mvc4

i don't know if solution provided allows flexibility though, let me know if i'm wrong.

honestly, flexible way have controller return json. more work asp.net mvc more times wish has raw json work with. following contrived example where

the controller code similar to:

    [httppost]     [outputcache(nostore = true, duration = 0, varybyparam = "*")]     public jsonresult login(loginview login)     {             if (!modelstate.isvalid)         {             var errors = modelstate.select(kvp => kvp.value.errors.select(e => e.errormessage));              return json(new { success = "false", message = errors });         }         //perform whatever actions need         // return json(response);     } 

and have function executed onsuccess similar to:

@using (ajax.beginform("login", "home", new ajaxoptions         {             httpmethod = "post",             onbegin = "loginbegin",             onsuccess = "loginsuccess"         }))         {              //you create modelview elsewhere , add properties need              var login = new inputloginview();              login.rememberme = true;               //form code here         } 

where loginsuccess javascript function similar to:

function loginsuccess(result) {     if (result.success) {         window.location = result.returnurl;     }     else {         //whatever actions want take         $('#login_password').val('');         $('#login-btn').button('reset');         var msg = new alertmsg();         msg.title = 'login problem';         msg.body = result.message;         $('#alerterror').trigger('show', msg);     } } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -